다음과 같이 간체 Base
에서 파생 된 유형은 거의 없습니다.오버로드 "기본"생성자 또는 "이"생성자?
생성자를 오버로드 할 때 기본 클래스의 생성자를 사용할지 또는 this
생성자를 사용할지 확실하지 않습니다.
ConcreteB
과부하 처음 두 과부하 this
사용시
ConcreteA
과부하 생성자 순전히 base
생성자를 사용.
생성자를 오버로드하는 더 좋은 방법은 무엇입니까?
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)
{
}
}
[편집] 그것은 이안 퀴 글리는 answer 이해가 듯 자신에 제시된 것을 보이는 . 유효성 검사기를 초기화하는 호출이있는 경우 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() {}
}
이것은 콘크리트 생성자에서 다른 초기화 작업을 수행해야하는 경우에 의미가있는 것처럼 보입니다. – Sung
예, "this"는 하루가 끝날 때 항상 "base"를 호출합니다. 그래서 "this"가 아무것도하지 않더라도, "base" –