我从某个地方获取了AAA类的对象,我想在该对象中添加更多信息。因此,我正在创建一个从AAA派生的新类BBB。BBB类具有其他字段字典。我在派生类构造函数中填充此字典,该类构造函数使用AAA类对象和要用作字典键的项数组,并且此字典的值是AAA类对象字段的元素。我试图在打击示例代码中创建类似的场景:
void Main(){
A obj = new A () ;
obj.prop1 = new int [] {5 ,10, 15} ;
obj.prop2 = "Hello" ;
obj.prop3 = "World" ;
// obj.Dump () ;
B obj2 = new B (new int [] {1,2,3}, obj) ;
// obj2.Dump () ;
}
// Define other methods and classes here
public class A {
public int [] prop1 ;
public string prop2 ;
public string prop3 ;
}
public class B : A {
public Dictionary <int, int> prop4 ;
public B (int [] keys, A a) {
prop4 = new Dictionary <int, int> () ;
if (keys.Length == a.prop1.Length ) {
for (int i = 0 ; i < keys.Length ; i++ ) {
prop4.Add (keys[i], a.prop1[i]) ;
}
// is there a way to obsolete below lines of code???
this.prop1 = a.prop1 ;
this.prop2 = a.prop2 ;
this.prop3 = a.prop3 ;
}
else {
throw new Exception ("something wrong") ;
}
}
}
在派生类构造函数中,我手动填充属性,但我不想这样做。还有另一种方法可以做到这一点。我的实际课堂上有20多个属性。
无法满足您的要求,但建议A
您为类创建一个副本构造函数,并将其与您的类B
构造函数一起使用:
// Define other methods and classes here
public class A
{
public int[] prop1;
public string prop2;
public string prop3;
public A()
{
}
public A(A orig)
{
prop1 = orig.prop1;
prop2 = orig.prop2;
prop3 = orig.prop3;
}
}
public class B : A
{
public Dictionary<int, int> prop4;
public B(int[] keys, A a) : base( a )
{
prop4 = new Dictionary<int, int>();
if (keys.Length == prop1.Length)
{
for (int i = 0; i < keys.Length; i++)
{
prop4.Add(keys[i], prop1[i]);
}
}
else
{
throw new Exception("something wrong");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句