在这种情况下,为什么 C# 无法解析正确的重载?
Why cannot C# resolve the correct overload in this case?
我遇到了一个很奇怪的情况,它是明确的,但重载解析器并不这么认为。考虑:
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
重载不明确?
可能是因为https://msdn.microsoft.com/en-us/library/aa691131%28v=vs.71%29.aspx
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
之间的唯一区别在于 return 值。
更具体地说: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.
我遇到了一个很奇怪的情况,它是明确的,但重载解析器并不这么认为。考虑:
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
重载不明确?
可能是因为https://msdn.microsoft.com/en-us/library/aa691131%28v=vs.71%29.aspx
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
之间的唯一区别在于 return 值。
更具体地说: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.