c#继承和转换继承层次结构

时间:2011-01-27 11:25:06

标签: c# inheritance

我想从类型A的现有对象创建类型B的新对象.B继承自A.我想确保将类型A的对象中的所有属性值复制到对象B型是什么?实现这一目标的最佳方法是什么?

class A
{
     public int Foo{get; set;}
     public int Bar{get; set;}
}

class B : A
{
    public int Hello{get; set;}
}


class MyApp{
    public A getA(){
         return new A(){ Foo = 1, Bar = 3 };
    }

    public B getB(){
         A myA = getA();
         B myB = myA as B; //invalid, but this would be a very easy way to copy over the property values!
         myB.Hello = 5;
         return myB;
    }

    public B getBAlternative(){
         A myA = getA();
         B myB = new B();

         //copy over myA's property values to myB
         //is there a better way of doing the below, as it could get very tiresome for large numbers of properties
         myB.Foo = myA.Foo;
         myB.Bar = myA.Bar;

         myB.Hello = 5;
         return myB;
    }
}

3 个答案:

答案 0 :(得分:4)

class A {
    public int Foo { get; set; }
    public int Bar { get; set; }

    public A() { }

    public A(A a) {
        Foo = a.Foo;
        Bar = a.Bar;
    }
}

class B : A {
    public int Hello { get; set; }

    public B()
        : base() {

    }

    public B(A a)
        : base(a) {

    }
}

修改

如果您不想复制每个属性,可以使A和B可序列化并序列化您的A实例(比如说流到Stream,而不是文件)并使用它初始化您的B实例。但我警告你,这很恶心,并且有很多开销:

A a = new A() {
    Bar = 1,
    Foo = 3
};

System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(A));
System.IO.Stream s = new System.IO.MemoryStream();
xs.Serialize(s, a);

string serial = System.Text.ASCIIEncoding.ASCII.GetString(ReadToEnd(s));
serial = serial.Replace("<A xmlns", "<B xmlns");
serial = serial.Replace("</A>", "</B>");

s.SetLength(0);
byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(serial);
s.Write(bytes, 0, bytes.Length);
s.Position = 0;

xs = new System.Xml.Serialization.XmlSerializer(typeof(B));
B b = xs.Deserialize(s) as B;

您可以在ReadToEnd here上获得更多信息。

答案 1 :(得分:3)

您可以为B:

定义显式的强制转换运算符
   public static explicit operator B(A a) 
   {
     B b = new B();
     b.Foo = a.Foo;
     b.Bar = a.Bar;
     b.Hello = 5;
     return b;
   }

所以你可以这样做:

B myB = (B)myA;

答案 2 :(得分:0)

这在OO机制中是不可能的,但是为此用途创建了AutoMapper