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

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

有人可以向我解释为什么在以下第三次调用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似乎不能隐含地获取上下文.

原文地址:https://www.jb51.cc/csharp/94583.html

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

相关推荐