我有这个扩展方法
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
因为从 int
到 int
的“转换”比从 int
到 object
的转换“更好” >,选择了 int
重载。
请注意,这适用于所有 重载,而不是仅 扩展方法(尽管打破扩展和非扩展方法之间的联系有不同的规则)。
关于c# - 扩展方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33610506/