推广方法解析方法

2023-09-04 01:17:53 作者:心比天高,

我写了一个扩展方法的字符串得到一个char参数, string.Remove(字符)。但是,当我用这个,而是它称为默认 string.Remove(INT)方法。

I wrote an extension method for String to get a char argument, string.Remove(char). But when I used this, it instead called the default string.Remove(int) method.

应该不是一个实际的方法presence的优先级高于隐式转换?

Shouldn't the presence of an actual method have higher priority than an implicit conversion?

推荐答案

实例方法优先于扩展方法。你的看法是相同的证明。

Instance methods have priority over extension methods. Your observation is proof of the same.

在解析调用哪个方法,它始终会选择一个匹配的实例方法通过一个扩展方法......这是直观的方式。

When resolving which method to call, it will always pick a matching instance method over an extension method... which is intuitive in a way.

从C#深入转述,

当编译器看到你是   试图调用一种方法,它看起来   就像一个实例方法,但不能   找到一个,它的然后查找   扩展方法(可见的   根据你的使用指令)。在   如果是多候选人的中   目标扩展方法,一个与   更好的转换相似   超载(例如,如果ICHILD和IBase的   都有类似的扩展方法   定义.. IChild.ExtensionMethod是   选择)

When the compiler sees that you're trying to call a method which looks like an instance method but is unable to find one, it then looks for extension methods (that are visible based on your using directives). In case of multiple candidates as the target extension method, the one with "better conversion" similar to overloading (e.g. if IChild and IBase both have a similar extension method defined.. IChild.ExtensionMethod is chosen)

还有一个隐藏的code断路器可以让我们说类型A没有SecretMethod在Libv1.0实例方法。所以,你写的扩展方法SecretMethod。如果笔者给大家介绍的相同名称的V2.0实例方法和签名(SANS的参数),并且您重新编译您的源最新-N-最大Libv2.0,所有现有调用扩展方法会默默地现在被路由到新的实例方法。

Also a hidden code-breaker could be lets say TypeA didn't have SecretMethod as an instance method in Libv1.0. So you write an extension method SecretMethod. If the author introduces an instance method of the same name and signature in v2.0 (sans the this param), and you recompile your source with the latest-n-greatest Libv2.0, all existing calls to the extension method would silently now be routed to the new instance method.