考虑有以下代码:
公共类TheBase { public int 1{ get;set;} public int 2{ get;set;} public int 3{ get;set;}公共int 3{ get;set;}公共类派生: TheBase { public派生(TheBase theBase) {1= theBase.One;2= theBase.Two;3= theBase.Three;} public int 4{ get;set;} public int 5{get;set;}}
是否有更简单的方法将属性“1”、“2”和“3”从基类传递给派生类?是否有一种整洁的黑客,或这是最好的解决方案,这样的问题?
发布于 2019-08-29 10:13:49
这是适当的实施:
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;
}
}发布于 2019-08-29 13:00:00
只需处理派生类,就好像基类属性是在派生类中创建的一样。提示:使用适当的修饰符来保持事物的封装。类似于:
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;
}
}(为了知道哪些属性来自基类,我使用了这个“基”前缀,但当然没有必要)。
https://stackoverflow.com/questions/57707836
复制相似问题