c# - 在构造函数中传递默认值

标签 c# constructor overloading

我有一个类 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. each Pi has an identity conversion to the corresponding Qi), the following tie-breaking rules are applied, in order, to determine the better function member.

• If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

• Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ.

• Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. This can occur if both methods have params 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 then MP is better than MQ.

这意味着如果您有两个方法都具有适用的参数,但一个需要使用可选参数值而另一个不需要,则没有可选值的方法更好。

关于c# - 在构造函数中传递默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723462/

相关文章:

java - Constructor.newInstance() 不知道参数顺序?

typescript :基于输入值(枚举)的函数返回类型

java - 为什么这是程序的输出?

c# - 有没有办法以编程方式在模板图像上覆盖文本并创建输出图像文件(PNG 或 JPEG)?

c# - "Automatically insert all named arguments"在方法调用站点,在代码中

Python 和 Qt (PyQt) - 在调整大小事件之前调用方法

c# - 一系列重载方法的替代方案

c# - HQL 与 Linq 到对象

c# - Xaml 中的展开/折叠菜单

时间:2019-03-17 标签:c++: calling constructors via curly braces?