gpt4 book ai didi

c# - 在这种情况下,为什么 C# 无法解析正确的重载?

转载 作者:IT王子 更新时间:2023-10-29 04:33:47 25 4
gpt4 key购买 nike

我遇到过一个很奇怪的情况,它是明确的,但重载解析器并不这么认为。考虑:

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.

IntDelStringDel 的唯一区别在于返回值。

更具体地说: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# - 在这种情况下,为什么 C# 无法解析正确的重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28697092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com