2016-03-15 133 views
0

有没有办法将对象字段复制到派生类构造函数中的基类,而无需单独复制每个字段?在派生类构造函数中复制基类

例子:

public class A 
{ 
    int prop1 { get; set; } 
    int prop2 { get; set; } 
} 

public class B : A 
{ 
    public B(A a) 
    { 
     //base = a; doesn't work. 
     base.prop1 = a.prop1; 
     base.prop2 = a.prop2; 
    } 
} 

A a = new A(); 
B b = new B(a); 
+0

有没有办法了这一点。 –

回答

0

我不能为我的生命明白你为什么要这么做

你传入Base类的一个实例为派生类的构造函数。你想做什么?

你试过this = a而不是base = a

+1

我想他试图从A的一个实例开始,然后创建一个B的新实例。他希望B从A继承的属性由A实例上的值填充,但不想手动输入他们出去分配他们。 –

+2

这是一个“复制构造函数”,并不少见。 –

0

成员是私人的,所以你甚至不能从派生类访问它们。即使它们是protected,您仍然无法通过B类的A实例访问它们。

为了做到这一点没有反映,会员必须是public:

public class A 
{ 
    public int prop1 { get; set; } 
    public int prop2 { get; set; } 
} 

// Define other methods and classes here 
public class B : A 
{ 
    public B(A a) 
    { 
     //base = a; doesn't work. 
     base.prop1 = a.prop1; 
     base.prop2 = a.prop2; 
    } 
} 
-1

如果你真的想这样做,而不能访问通过继承的属性,那么你可以通过这样的反思这样做:

public class Aclass 
{ 
    public int Prop1 { get; set; } 
    public int Prop2 { get; set; } 
} 

public class Bclass : Aclass 
{ 
    public Bclass(Aclass aInstance) 
    { 
     CopyPropertiesFromAltInstance(aInstance); 
    } 

    public void CopyPropertiesFromAltInstance(Aclass aInstance) 
    { 
     PropertyInfo[] aProperties = aInstance.GetType().GetProperties(); 
     PropertyInfo[] myProperties = this.GetType().GetProperties(); 
     foreach (PropertyInfo aProperty in aProperties) 
     { 
      foreach (PropertyInfo myProperty in myProperties) 
      { 
       if (myProperty.Name == aProperty.Name && myProperty.PropertyType == aProperty.PropertyType) 
       { 
        myProperty.SetValue(this, aProperty.GetValue(aInstance)); 
       } 
      } 
     } 
    } 
} 
+0

你不能将'A'投射到'B'。 'A'是基类。 –

0
public class A 
{ 
    public A(A a) 
    { 
     prop1 = a.prop1; 
     prop2 = a.prop2; 
    } 

    int prop1 { get; set; } 
    int prop2 { get; set; } 
} 

public class B : A 
{ 

    public B(A a) : base (a) 
    { 

    } 
} 

A a = new A(); 
B b = new B(a); 

这样的事情,虽然我不知道这是否是语法正确的,因为我没有编译。您应该在子类的构造函数之后使用base关键字将它的依赖项的值传递给基类。

编辑:但我只是意识到你正在传递一个基类到一个子类。这是一个设计缺陷。

0

这听起来像你想要从AB添加所有属性,而无需单独指定它们。如果你不想不断地向构造函数中添加新的元素,你可以使用反射来为你完成工作。

public B(A a) 
{ 
    var bType = this.GetType(); 

    // specify that we're only interested in public properties 
    var aProps = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 

    // iterate through all the public properties in A 
    foreach (var prop in aProps) 
    { 
     // for each A property, set the same B property to its value 
     bType.GetProperty(prop.Name).SetValue(this, prop.GetValue(a)); 
    } 
} 

关于这个的几个注意事项:

  • 上述代码设置公共实例属性,所以你需要在A改变你的属性是公共的。
  • 因为你知道B包含A一切(因为它是从它派生的),我只认为这是安全的。
  • 如果您只有一些属性,特别是如果它们不经常更改,只需单独列出它们......您将更容易地看到您的代码正在做什么。
相关问题