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

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

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

问题描述

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

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

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

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


解决方案


在这种情况下,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?

解决方案

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:

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

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

08-01 05:35