Есть два способа реализовать перегрузки. Первый - делать все в одном методе / конструкторе и вызывать его из других перегрузок, что приводит к более длинным телам методов . Второй - делать минимум в каждой перегрузке, поэтому код иногда трудно перемещаться и понимать, какая перегрузка что делает.
Например, если две перегрузки класса Cat
:
public Cat(string name, int? weight, Color mainColor);
public Cat(string name);
есть два способа реализовать это:
public Cat(string name, int? weight, Color mainColor)
{
// Initialize everything.
this.name = name;
if (weight.HasValue) this.weight = weight.Value;
// There is a bug here (see the anwer of @Timwi): mainColor can be null.
this.colors = new List<Colors>(new[] { mainColor });
}
public Cat(string name)
: this(name, null, null)
{
// Nothing else to do: everything is done in the overload.
}
public Cat(string name)
{
// Initialize the minimum.
this.name = name;
this.colors = new List<Colors>();
}
public Cat(string name, int? weight, Color mainColor)
: this(name)
{
// Do the remaining work, not done in the overload.
if (weight.HasValue) this.weight = weight.Value;
this.colors.Add(mainColor);
}
Примечание: поскольку C # 4.0 позволяет указывать необязательные параметры во избежание двусмысленности, допустим, я говорю только о C # 3.0.