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

c# – 为什么不能直接调用扩展方法?

发布时间:2020-12-15 06:48:10 所属栏目:百科 来源:网络整理
导读:有人可以向我解释为什么在以下第三次调用DoSomething是无效的? (错误消息是“当前上下文中不存在”DoSomething“的名称)” public class A { }public class B : A{ public void WhyNotDirect() { var a = new A(); a.DoSomething(); // OK this.DoSomething
有人可以向我解释为什么在以下第三次调用DoSomething是无效的?
(错误消息是“当前上下文中不存在”DoSomething“的名称)”
public class A { }
public class B : A
{
    public void WhyNotDirect()
    {
        var a = new A();
        a.DoSomething();  // OK
        this.DoSomething();  // OK
        DoSomething(); // ?? Why Not
    }
}
public static class A_Ext
{
    public static void DoSomething(this A a)
    {
        Console.WriteLine("OK");
    }
}

解决方法

扩展方法仍然是静态方法,而不是真实的实例调用.为了使其工作,您将需要使用实例方法语法(来自 Extension Methods (C# Programming Guide))的特定上下文

In your code you invoke the extension
method with instance method syntax.
However,the intermediate language
(IL) generated by the compiler
translates your code into a call on
the static method. Therefore,the
principle of encapsulation is not
really being violated. In fact,
extension methods cannot access
private variables in the type they are
extending.

因此,通常情况下,两种语法都可以正常工作,第二种语言没有明确的上下文,而且生成的IL似乎不能隐含地获取上下文.

(编辑:李大同)

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

    推荐文章
      热点阅读