Why cannot C# resolve the correct overload in this case?

三世轮回 提交于 2020-01-03 06:45:11

问题


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!
    }
}

How come the call to ParamTest overloads is resolved correctly, but Test overload is ambiguous?


回答1:


Perhaps because 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.

And the only difference between IntDel and StringDel is in the return value.

More specifically: 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.



来源:https://stackoverflow.com/questions/28697092/why-cannot-c-sharp-resolve-the-correct-overload-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!