c# – 为什么扩展方法表现不同?

前端之家收集整理的这篇文章主要介绍了c# – 为什么扩展方法表现不同?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
派生类包含一个“计数”方法,它对类“派生”执行一些操作.另一方面,我有一个扩展方法,它也是“派生”类的目标.
Derived derived = new Derived();
derived.Count();

通过调用上面的代码片段将在派生类中执行“Count”方法.为什么C#编译器在这种情况下不会警告并识别扩展方法.框架内部如何处理这个?

//Base class
public class Base
{
    public virtual string Count()
    {
        return string.Empty;
    }
}

//Derived class
public class Derived : Base
{
    public override string Count()
    {
        return base.Count();
    }
}

//Extension Methods for Derived class
public static class ExtensionMethods
{
    public static Derived Count(this Derived value)
    {
        return new Derived();
    }
}

解决方法

规范(第7.6.5.2节)明确指出实例方法优先于扩展方法

if the normal processing of the invocation finds no applicable methods,an attempt is made to process the construct as an extension method invocation.

The preceding rules mean that instance methods take precedence over extension methods,that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations,and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive. For example:

如果实例方法与传递的参数匹配,则甚至不考虑扩展方法.

猜你在找的C#相关文章