gpt4 book ai didi

c# - C#如何解决不同的扩展方法重载?

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:02 24 4
gpt4 key购买 nike

我有如下代码片段:

public static class M
{
public static int Plus(this int i, int p=6)
{
return i + p;
}
}
public static class N
{
public static int Plus(this int i)
{
return i + 10;
}
}
class Program
{
static void Main()
{
int i = 3.Plus();
Console.WriteLine(i);
}
}

运行程序,输出“13”,表示调用了类N的扩展方法。为什么M类的方法不匹配?

然后如果我删除类 N,好的,类 M 的扩展方法被调用,它按预期输出“9”。

所以我的问题是,在 C# 或 .net 框架中是否有规则来确定,如果存在多个匹配项,将调用哪个扩展方法?这与重载决议规则或其他什么有关吗?

非常感谢。

最佳答案

与所有其他方法一样,相同的重载规则适用于扩展方法。使用 N 是因为它是更好的匹配。 M 可能有一个可选参数,但无参数选项更合适,因为规则倾向于参数最少的选项。

来自 Named and Optional Arguments (C# Programming Guide) :

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

然而,“接近度”也与扩展方法一起发挥作用,如 Eric Lippert's blog 中所述。 :

这样做的结果是,如果您将代码重组为:

namespace X
{
public static class N
{
public static int Plus(this int i)
{
return i + 10;
}
}
}

namespace ConsoleApplication1
{
public static class M
{
public static int Plus(this int i, int p = 6)
{
return i + p;
}
}

internal class Program
{
private static void Main()
{
int i = 3.Plus();
Console.WriteLine(i);
}
}
}

然后显示的数字是9。换句话说,选择具有可选参数的版本是因为它位于同一命名空间中,因此“更接近”。

关于c# - C#如何解决不同的扩展方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864666/

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