c# - 扩展方法重载

标签 c# extension-methods

我有这个扩展方法

public static class Extensions
{
     public static void ConsoleWriteLine(this object Value)
     {
         Console.WriteLine(Value);
     }
}

对于整数值我有一点修改

public static void ConsoleWriteLine(this int Value)
{
    Console.WriteLine("Integer: " + Value);
}

我的问题是:当我写 int x = 1; x.ConsoleWriteLine(); 在这种情况下,是什么决定进行第二次延期? int 也是一个object

最佳答案

what makes the decision to take the second extension in this case?

当编译器有多个有效方法可供选择时,它使用一组重载决议规则来确定它应该绑定(bind)到哪个方法。第二个扩展方法与调用签名完全匹配,所以选择它。由于任何其他类型都可以直接转换为object,因此将选择第一个扩展。其他数字类型可以隐式转换为 int,但隐式转换并不比直接转换为父类“更好”。

我相信这里的相关规范是 7.5.3.2:

7.5.3.2 Better function member

For the purposes of determining the better function member, a stripped-down argument list A is constructed containing just the argument expressions themselves in the order they appear in the original argument list. Parameter lists for each of the candidate function members are constructed in the following way:

...

Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, MP is defined to be a better function member than MQ if

  • for each argument, the implicit conversion from EX to QX is not better than the implicit conversion from EX to PX, and

因为从 intint 的“转换”比从 intobject 的转换“更好” >,选择了 int 重载。

请注意,这适用于所有 重载,而不是 扩展方法(尽管打破扩展和非扩展方法之间的联系有不同的规则)。

关于c# - 扩展方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33610506/

相关文章:

c# - 无法从程序集 'mscorlib 加载类型 'System.Runtime.CompilerServices.ExtensionAttribute',版本 = 4.0.0.0 错误

c# - 为什么这个通用扩展方法不能编译?

c# - 如果我想将类型约束 (T=int) 方法添加到泛型 (T) 类中,是否必须创建扩展方法?

c# - 是否可以将 unicode hex\u0092 显示(转换?)为 .NET 中的 unicode html 实体?

c# - C# 中 List<List<Coordinate>> 的优雅初始化方式

c# - 这是对 ExtensionMethod 的良好使用吗?

c# - 如何将索引器与具有参数和函数调用的扩展方法一起使用

c# - 静态类的扩展方法?

c# - 如何引用 UDF 中的一系列单元格

c# - 为什么在使用静态导入时不能将扩展方法作为静态方法调用?