加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:43:04 所属栏目:百科 来源:网络整理
导读:派生类包含一个“计数”方法,它对类“派生”执行一些操作.另一方面,我有一个扩展方法,它也是“派生”类的目标. Derived derived = new Derived();derived.Count(); 通过调用上面的代码片段将在派生类中执行“Count”方法.为什么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:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读