本文介绍了C#4.0以及可选参数和重载的组合是否会向您发出有关歧义的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我已经开始阅读乔恩·斯凯特(Jon Skeet)的书的早期版本,其中包含有关C#4.0的各个部分,有一件事令我震惊.不幸的是,我没有Visual Studio 2010,因此我想我只是在这里问一下,看看是否有人知道答案.

I've started reading Jon Skeet's early access version of his book, which contains sections on C# 4.0, and one thing struck me. Unfortunately I don't have Visual Studio 2010 available so I thought I'd just ask here instead and see if anyone knew the answer.

如果我有以下代码,请结合使用现有代码和新代码:

If I have the following code, a mixture of existing code, and new code:

public void SomeMethod(Int32 x, Int32 y) { ... }

public void SomeMethod(Int32 x, Int32 y, Int32 z = 0) { ... }

编译器会在定义站点还是在调用站点抱怨可能存在的歧义?

Will the compiler complain either at the definition site or the call site about possible ambiguity?

例如,这段代码实际上将做什么?

For instance, what will this piece of code actually do?

SomeClass sc = new SomeClass();
sc.SomeMethod(15, 23);

会编译吗?它会调用不带z参数的那个,还是会调用带z参数的那个?

Will it compile? Will it call the one without the z parameter, or will it call the one with the z parameter?

推荐答案

它将在没有警告的情况下进行编译,并将选择第一个重载.

It will compile without warnings and will choose the first overload.

随着可选参数和命名参数的引入,C#的重载解析机制变得非常复杂.但是,在这种特定情况下,这是有道理的.与往常一样,编译器将选择与参数匹配的最具体的重载.

With the introduction of optional and named parameters, the overload resolution mechanism of C# has become really complicated. In this specific case, it makes sense however. As usual, the compiler will choose the most specific overload that matches the arguments.

我不认为此特定情况与C#1.0有什么大不同:

I don't believe this specific case is much different from C# 1.0:

public void SomeMethod(Int32 x, Int32 y) { }
public void SomeMethod(Int32 x, Int32 y, params Int32[] z) { }

(在重载分辨率方面)工作原理相同.

which works identically (in terms of overload resolution).

关注答案:我不这样认为.恐怕您将不得不在方法调用中手动指定默认参数.但是,如果xy参数具有不同的名称,例如:

Follow up answer: I don't think so. I'm afraid you'll have to manually specify the default argument in the method call. However, if x or y parameter had a different name like:

public void SomeMethod(Int32 x, Int32 y) { }
public void SomeMethod(Int32 t, Int32 y, Int32 z = 0) { }

您可以选择第二个过载:

you could choose the second overload with:

obj.SomeMethod(t: 10, y: 20);

这篇关于C#4.0以及可选参数和重载的组合是否会向您发出有关歧义的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:50