将基类的属性传递给派生类的更好方法?

Sup*_*Bob 2 c# .net-core

考虑使用以下代码:

public class TheBase
{
   public int One { get; set; }
   public int Two { get; set; }
   public int Three { get; set; }
}

public class Derived : TheBase
{
   public Derived(TheBase theBase)
   {
      One = theBase.One;
      Two = theBase.Two;
      Three = theBase.Three;
   }

   public int Four { get; set; }
   public int Five { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法可以将基类的“一个”,“两个”和“三个”属性传递给派生类?是否有某种灵巧的hack,或者这是解决此类问题的最佳选择?

Mar*_*rno 8

这是正确的实现:

public class TheBase
{
    public int One { get; set; }
    public int Two { get; set; }
    public int Three { get; set; }
    public TheBase(int one, int two, int three)
    {
        One = one;
        Two = two;
        Three = three;
    }
    public TheBase(TheBase theBase)
    {
        One = theBase.One;
        Two = theBase.Two;
        Three = theBase.Three;
    }
}
public class Derived : TheBase
{
    public int Four { get; set; }
    public int Five { get; set; }
    public Derived(TheBase theBase, int four, int five) : base(theBase)
    {
        Four = four;
        Five = five;
    }
    public Derived(int one, int two, int three, int four, int five) : base(one, two, three)
    {
        Four = four;
        Five = five;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不过,他想解决什么问题?为什么对象初始化器语法不够? (3认同)