构造函数使用默认参数重载 [英] Constructor Overloading with Default Parameters

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

问题描述

我不小心重载在C#构造函数如下:

 公共MyClass的(字符串MyString的)
{
//一些代码放在这里
}

公共MyClass的(字符串MyString的,布尔myParameter = FALSE)
{
//一些不同的代码在这里
}

有了这个代码,我的项目编译罚款。如果我调用构造函数只是一个字符串参数,如何C#我决定要使用哪个构造?为什么这个功能语法允许的?


解决方案

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




在IL中,产生的第二个构造仍是两个参数。唯一的区别是,第二个参数具有提供的默认值的属性



至于编译而言,第一个是在技术上仍当调用一个更适合有一个字符串构造函数。当你调用这个带一个参数,最好的搭配是第一个构造函数,第二个将不被调用。



C#的规范阐明了这一点。在7.5中,它指出:......实例构造函数,使用重载决策来确定一组候选函数成员的调用。具体的规则,然后在7.5.3.2,在这个特定的规则适用规定:




否则,如果MP的所有参数都有相应的参数,而默认参数需要被取代的MQ的至少一个可选参数则MP比MQ好




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


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
}

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?

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.

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.

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:

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.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆