我有一个类 Executive,该类的代码如下:
public class Executive
{
public Executive(int Id = 0)
{
// Constructor 1
this.BaseSalary = 3000;
Console.Write("DONE");
}
public Executive()
{
// Constructor 2
Console.Write("done");
}
}
主要我做了以下事情:
Executive exec = new Executive()
它总是调用构造函数 2。
为什么它不调用构造函数 1(因为 Id 具有默认值)?
最佳答案
这就是确定最佳调用方法的方式。执行重载决议时,没有指定值的可选参数将从参数列表中删除:
7.5.3.2 Better function member
For the purposes of determining the better function member, a stripped-down argument list
A
is constructed containing just the argument expressions themselves in the order they appear in the original argument list. Parameter lists for each of the candidate function members are constructed in the following way:• The expanded form is used if the function member was applicable only in the expanded form.
• Optional parameters with no corresponding arguments are removed from the parameter list
• The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list.
同样在同一段落的后面:
In case the parameter type sequences
{P1, P2, …, PN}
and{Q1, Q2, …, QN}
are equivalent (i.e. eachPi
has an identity conversion to the correspondingQi
), the following tie-breaking rules are applied, in order, to determine the better function member.• If
MP
is a non-generic method andMQ
is a generic method, thenMP
is better thanMQ
.• Otherwise, if
MP
is applicable in its normal form andMQ
has a params array and is applicable only in its expanded form, then MP is better thanMQ
.• Otherwise, if
MP
has more declared parameters thanMQ
, thenMP
is better thanMQ
. This can occur if both methods haveparams
arrays and are applicable only in their expanded forms.• Otherwise if all parameters of MP have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in
MQ
thenMP
is better thanMQ
.
这意味着如果您有两个方法都具有适用的参数,但一个需要使用可选参数值而另一个不需要,则没有可选值的方法更好。
关于c# - 在构造函数中传递默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723462/