我想从现有的 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;
}
}
最佳答案
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 的实例(比如流,而不是文件)并用它初始化 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 .
关于c# 继承和向下继承层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815703/