在派生类构造函数中复制基类

时间:2016-03-15 22:53:15

标签: c#

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

示例:

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);

5 个答案:

答案 0 :(得分:0)

我无法理解你为什么要这样做

您正在将Base类的实例传递给派生类的构造函数。你想做什么?

您是否尝试过this = a而不是base = a

答案 1 :(得分:0)

成员是私有的,因此您甚至无法从派生类访问它们。即使它们是protected,您仍然无法在A类的B实例上访问它们。

为了在没有反思的情况下做到这一点,成员必须公开:

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;
   }
}

答案 2 :(得分: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关键字将其依赖项的值传递给基类。

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

答案 3 :(得分:0)

听起来您想要将A的所有属性添加到B,而无需单独指定它们。如果您不想继续向构造函数添加新的,您可以使用反射为您完成工作。

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中的所有内容(因为它来自它)。
  • 如果您只有一些属性,特别是如果它们不经常更改,只需单独列出它们......它就会更容易看到您的代码正在做什么。

答案 4 :(得分:-1)

如果你真的想这样做并且无法通过继承访问属性,那么你可以通过这样的反射来做:

{{1}}
相关问题