有两种实现重载的方法。第一种是在一个方法/构造函数中完成所有操作,并从其他重载方法中调用它,这会导致方法体变得更长。第二种方法是在每个重载中只做最少的工作,因此有时代码难以导航和理解哪个重载执行了什么。
例如,如果一个类 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。