【发布时间】:2011-06-16 11:41:33
【问题描述】:
我想从 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;
}
}
【问题讨论】:
标签: c# inheritance