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

时间:2019-08-29 10:07:26

标签: 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; }
}

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

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:-1)

只需使用派生类,就好像在派生类中创建了基类属性一样。 提示:使用适当的修饰符可以使内容封装。像这样:

public abstract class TheBase
{
   protected int baseOne { get; set; }
   protected int baseTwo { get; set; }
   protected int baseThree { get; set; }
}

public class Derived : TheBase
{
   public int Four { get; set; }
   public int Five { get; set; }

   public void SomeCode()
   {
       baseOne = 1;
       baseTwo = 2;
       baseThree = 3;
       Four = 4;
       Five = 5;
   }
}

(我使用此“基”前缀来了解哪些属性来自基类,但当然不是必须的。)