为什么你能不能直接调用扩展方法? [英] Why can you not invoke extension methods directly?

查看:108
本文介绍了为什么你能不能直接调用扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释我为什么在DoSomething的下列第3调用是无效的?
(错误消息DoSomething的'这个名字并不在目前的情况下存在)

 大众A级{} 
公共b类:A
{
公共无效WhyNotDirect()
{
VAR一个=新的A();
a.DoSomething(); // OK
this.DoSomething(); // OK
DoSomething的(); //?为什么不
}
}
公共静态类A_Ext
{
公共静态无效DoSomething的(这方面的一个一)
{
Console.WriteLine (好);
}
}


解决方案

扩展方法仍然是静态方法,不是真正的实例调用。为了使这个工作,你会使用实例方法语法(从扩展方法需要特定的上下文(C#编程指南)




在你的代码中调用与实例方法语法扩展
法。
然而,编译器
产生的中间语言
(IL)你的代码翻译成上
静态方法的调用。因此,封装的
原理并不
真正被侵犯。事实上,
扩展方法不能访问他们延长
类型
私有变量。




因此,虽然通常情况下,两种语法会的工作,二是没有明确的情况下,它会似乎是IL产生不能隐式获取上下文。


Can someone explain to me why in the following the 3rd invocation of DoSomething is invalid? ( Error message is "The name 'DoSomething' does not exist in the current context" )

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 are still static methods, not true instance calls. In order for this to work you would need specific context using instance method syntax (from 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.

So while normally, both syntaxes would work, the second is without explicit context, and it would seem that the IL generated can't obtain the context implicitly.

这篇关于为什么你能不能直接调用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆