我想从一个已有的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;
}
}