微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐