在这种情况下,为什么C#无法解决正确的重载?
我遇到了一个非常模糊的奇怪情况,但过载解析器并不这么认为。 考虑:
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
方法的签名特别不包括返回类型,也不包括可以为最右边的参数指定的params修饰符。
IntDel
和StringDel
之间的唯一区别在于返回值。
更具体地说: https : //msdn.microsoft.com/en-us/library/ms173171.aspx
在方法重载的上下文中,方法的签名不包括返回值。 但是在代理的上下文中,签名确实包含了返回值。 换句话说,方法必须具有与委托相同的返回类型。