タイプBの新しいオブジェクトをタイプAの既存のオブジェクトから作成したいと思います.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;
}
}
+1 - 私はコンストラクターのアプローチも好むでしょう。 – nulltoken
シリアライザコードを追加していただきありがとうございます。おそらく、すべてのメンバーをループして値をコピーするためにリフレクションを使用することもできますが、それにはオーバーヘッドが多くなります。 –