1

伙计们,我想知道是否有可能做这样的事情:

class A
{
  prop T1

  prop T2

  prop T3

  prop T4
}

class B : A
{
  prop T5
}

然后将 A 转换为 B。

A a = new A();
B b = a;

也许有一些用于此类事情的静态转换器类,所以代码可能看起来像这样。

A a = new A();
B b = null;
UltimativeCaster.BaseclassCast(a, b);

如果这是一个重复的问题,我深表歉意。我希望你们能给我一些想法或解决方案或一些链接。

编辑:找到所有属性并复制过去值的任何算法。由于它的基类,属性将匹配。

4

5 回答 5

7

在 C# 中,对象的类型一旦创建就不能更改。

如果要将对象 A 的属性复制到对象 B,可以使用反射和以下通用算法:

    public B Convert<A, B>(A element) where B : A, new()
    {
        //get the interface's properties that implement both a getter and a setter
        IEnumerable<PropertyInfo> properties = typeof(A)
            .GetProperties()
            .Where(property => property.CanRead && property.CanWrite).ToList();

        //create new object
        B b = new B();

        //copy the property values to the new object
        foreach (var property in properties)
        {
            //read value
            object value = property.GetValue(element);

            //set value
            property.SetValue(b, value);
        }

        return b;
    }
于 2013-08-29T08:24:02.163 回答
4

您不能从 A 转换为 B,但也许您可以使用特定的构造函数,例如

public B(A a)
{
    this.T1 = a.T1;
    this.T2 = a.T2;
    ...
    this.T5 = defaultvalue;
}
于 2013-08-29T08:25:40.717 回答
4

由于 A 是 B 的超类,因此不可能将a转换为b。我认为您可能对以下内容感兴趣:

public B CreateB(A a)
{
   B b = new B();
   b.T1 = a.T1;
   b.T2 = a.T2;
   b.T3 = a.T3;
   b.T4 = a.T4;
   return b;
}

顺便说一句,您可能还对自动映射器库感兴趣,它可以为您完成工作,例如https://github.com/AutoMapper/AutoMapper

于 2013-08-29T08:28:24.183 回答
1

如果您需要更频繁地执行此操作,并且使用不同的类型,您可以考虑创建一个工厂类,从不同类型的源创建实例:

public static class BFactory
{
    public static B CreateFromA(A a)
    {
        B result = new B();

        result.T1 = a.T1;
        result.T2 = a.T2;
        result.T3 = a.T3;
        result.T4 = a.T4;
        result.T5 = 0;

        return result;
    }
}
于 2013-08-29T08:33:50.660 回答
0

你永远无法做到这一点。使用多态性将一种类型表示为另一种类型需要两种类型之间的“IS A”关系。因为A不是B这永远不会工作。

于 2013-08-29T08:29:01.780 回答