为什么在这种情况下C#无法解决正确的重载? [英] Why cannot C# resolve the correct overload in this case?
问题描述
我遇到了一个很明确的奇怪情况,但是过载解析器却不这么认为。考虑:
I've come across a strange situation which is non-ambiguous, yet the overload resolver doesn't think so. Consider:
public static class Program
{
delegate int IntDel();
delegate string StringDel();
delegate void ParamIntDel(int x);
delegate void ParamStringDel(string x);
static void Test(IntDel fun) { }
static void Test(StringDel fun) { }
static void ParamTest(ParamIntDel fun) { }
static void ParamTest(ParamStringDel fun) { }
static int X() { return 42; }
static void PX(int x) { }
public static void Main(string[] args)
{
ParamTest(PX); // OK
Test(X); // Ambiguos call!
}
}
如何呼叫 ParamTest
重载可以正确解决,但是 Test
重载是模棱两可的?
How come the call to ParamTest
overloads is resolved correctly, but Test
overload is ambiguous?
推荐答案
也许是因为 https: //msdn.microsoft.com/zh-CN/library/aa691131%28v=vs.71%29.aspx
方法的签名明确地不包括返回类型,也不包括可能为最右边的参数指定的params修饰符。
The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
IntDel
和 StringDel
之间的唯一区别是返回值。
And the only difference between IntDel
and StringDel
is in the return value.
更具体地说: https:// msdn。 microsoft.com/en-us/library/ms173171.aspx
在方法重载的情况下,
方法的签名不包含返回值。但是在委托的上下文中,签名确实包含返回值。换句话说,方法的返回类型必须与委托相同。
In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value. In other words, a method must have the same return type as the delegate.
这篇关于为什么在这种情况下C#无法解决正确的重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!