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

C# 将基类的属性传递给派生类的更好方法?,c#,.net-core,C#,.net Core,考虑使用以下代码: 是否有更简单的方法将属性“一”、“二”和“三”从基类传递到派生类?是否有某种简洁的破解方法可用,或者这是解决此类问题的最佳解决方案?这是正确的实现: 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

考虑使用以下代码:


是否有更简单的方法将属性“一”、“二”和“三”从基类传递到派生类?是否有某种简洁的破解方法可用,或者这是解决此类问题的最佳解决方案?

这是正确的实现:

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

只需处理派生类,就好像基类属性是在派生类中创建的一样。 提示:使用适当的修改器以保持封装。比如:

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

(我使用此“base”前缀是为了知道哪些属性来自基类,但这当然不是必需的)。

为什么要将
TheBase
的实例作为构造函数参数传递给
派生的
实例?如果基类上的属性是公共的/受保护的,您应该可以直接访问它们,不是吗?将基类的值复制到派生类的目的是什么?您想做什么?您可以使用一些反射并从基类复制所有属性。但这只是隐藏了复杂性,事实上,这与您的方法类似。你会遇到什么问题?对我来说似乎很正常。@rmszc81我需要返回另一个对象,其属性包括基本对象的属性,以及一些附加属性,如“四”和“五”。以后会定义它们。@himbrombere没有遇到任何问题!如果有比这更好的方法,这只是一个一般性的问题!不过,他想解决什么问题?为什么对象初始值设定项语法不够?@MarcoSalemo谢谢,没有必要在构造函数中包含5和4,我知道我可以这样做。我觉得两种方法都可以。只是确保没有比这里显示的实现更好的东西。这正是我的代码所显示的?我通过在派生类中创建基类的属性来处理派生类。是的,但是您将基类传递给派生类的构造函数。这是没有必要的。您可以直接访问基类属性。请告诉我,当基类属性不存在时,如何访问它们?我提出的代码和问题是关于构造函数的,以及如何从基类最有效地构造派生类。一旦从“TheBase”类继承了“派生”类,您就可以自动访问“TheBase”使用受保护或公共修饰符声明的属性和方法。似乎您再次误解了我的观点。为了从基类传递对象持有的属性,您需要将此类对象传递给派生对象的构造函数,或者执行Marco Salemo正在执行的操作。您的代码没有演示与当前主题相关的任何内容。它只是展示了如何使用一些方法(甚至不是构造函数)初始化属性。
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;
   }
}