我有几个从简化派生的类型,Base
如下所示。
我不确定this
在重载构造函数时是使用基类的构造函数还是构造函数。
ConcreteA
纯粹使用base
构造函数重载构造函数,而
ConcreteB
重载使用this
前两个重载。
重载构造函数的更好方法是什么?
public abstract class Base
{
public string Name { get; set; }
public int? Age { get; set; }
protected Base() : this(string.Empty) {}
protected Base(string name) : this(name, null) {}
protected Base(string name, int? age)
{
Name = name;
Age = age;
}
}
public class ConcreteA : Base
{
public ConcreteA(){}
public ConcreteA(string name) : base(name) {}
public ConcreteA(string name, int? age) : base(name, age)
{
}
}
public class ConcreteB : Base
{
public ConcreteB() : this(string.Empty, null){}
public ConcreteB(string name): this(name, null){}
public ConcreteB(string name, int? age) : base(name, age)
{
}
}
[编辑]
看起来伊恩·奎格利在他的回答中所建议的似乎是有道理的。如果我要进行初始化验证器的调用,ConcreteA(string)
则在以下情况下将永远不会初始化验证器。
public class ConcreteA : Base
{
public ConcreteA(){}
public ConcreteA(string name) : base(name) {}
public ConcreteA(string name, int? age) : base(name, age)
{
InitializeValidators();
}
private void InitializeValidators() {}
}