使用默认参数的构造函数重载

Constructor Overloading with Default Parameters(使用默认参数的构造函数重载)

本文介绍了使用默认参数的构造函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不小心在 C# 中重载了一个构造函数,如下所示:

I accidentally overloaded a constructor in C# as follows:

public MyClass(string myString) 
{
    // Some code goes here 
}

public MyClass(string myString, bool myParameter = false) 
{
   // Some different code here
}

使用此代码,我的项目编译得很好.如果我只用 string 参数调用构造函数,C# 如何决定我要使用哪个构造函数?为什么在语法上允许此功能?

With this code my project compiled fine. If I call the constructor with just a string argument, how does C# decide which constructor I want to use? Why is this functionality syntactically allowed?

推荐答案

为什么在语法上允许这个功能?

Why is this functionality syntactically allowed?

就生成的IL而言,第二个构造函数仍然是两个参数.唯一的区别是第二个参数有一个提供默认值的属性.

In terms of the IL generated, the second constructor is still two arguments. The only difference is that the second argument has an attribute providing the default value.

就编译器而言,当您使用单个字符串调用构造函数时,第一个在技术上仍然更合适.当您使用单个参数调用 this 时,最佳匹配是第一个构造函数,而第二个不会被调用.

As far as the compiler is concerned, the first is still technically a better fit when you call a constructor with a single string. When you call this with a single argument, the best match is the first constructor, and the second will not get called.

C# 规范说明了这一点.在 7.5 中,它声明......实例构造函数采用重载决议来确定要调用的候选函数成员集中的哪一个."然后在 7.5.3.2 中指定具体规则,该具体规则适用:

The C# specification spells this out. In 7.5, it states "... instance constructors employ overload resolution to determine which of a candidate set of function members to invoke." The specific rules are then specified in 7.5.3.2, where this specific rule applies:

否则,如果 MP 的所有参数都有对应的参数,而默认参数需要替换为 MQ 中的至少一个可选参数,则 MP 优于 MQ.

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.

在这种情况下,MP(您的第一个构造函数)具有所有参数,但 MQ(您的第二个)需要至少一个可选参数".

In this case, MP (your first constructor) has all arguments, but MQ (your second) needs "at least one optional parameter."

这篇关于使用默认参数的构造函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用默认参数的构造函数重载

基础教程推荐