简体   繁体   English

C#扩展方法优先级

[英]C# Extension method precedence

I'm a bit confused about how extension methods work. 我对扩展方法的工作原理有点困惑。

If I'm reading this correctly http://msdn.microsoft.com/en-us/library/bb383977.aspx and this If an extension method has the same signature as a method in the sealed class, what is the call precedence? 如果我正确地阅读这个http://msdn.microsoft.com/en-us/library/bb383977.aspx并且这个如果扩展方法与密封类中的方法具有相同的签名,那么调用优先级是什么? .

Then the following should write out "Instance", but instead it writes "Extension method". 然后以下应该写出“实例”,而是写入“扩展方法”。

interface IFoo
{
}

class Foo : IFoo
{
    public void Say()
    {
        Console.WriteLine("Instance");
    }
}

static class FooExts
{
    public static void Say(this IFoo foo)
    {
        Console.WriteLine("Extension method");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IFoo foo = new Foo();
        foo.Say();
    }
}

Appreciate any help in clarifying the behavior. 澄清澄清行为的任何帮助。

The big difference here is that you have defined an extension method for the IFoo interface, and your foo variable is of type IFoo . 这里最大的区别是你已经为IFoo接口定义了一个扩展方法,你的foo变量是IFoo类型。

If your code was to look like this: 如果你的代码看起来像这样:

Foo foo = new Foo();
foo.Say()

The Foo.Say() method would be executed, not the extension method. 将执行Foo.Say()方法,而不是扩展方法。

I wish I could give you a thorough explanation on why this is but I can only cover the basic mechanism. 我希望我能给你一个彻底的解释,为什么这是,但我只能涵盖基本机制。 As your variable was of IFoo type and not of Foo , when the compiler tried to determine what methods were available, it looked past any non-interface methods of the Foo class (as it should). 由于你的变量是IFoo类型而不是Foo ,当编译器试图确定哪些方法可用时,它看起来超过了Foo类的任何非接口方法(应该如此)。 However, the extension method Say() was available, so it invoked this. 但是,扩展方法Say()可用,因此它调用了它。

In your Main , foo is declared as IFoo . 在你的Mainfoo被声明为IFoo When the compiler looks for a method Say , it finds only the extension method. 当编译器查找方法Say ,它只找到扩展方法。 This is because the instance method is declared in Foo , not in IFoo . 这是因为实例方法是在Foo声明的,而不是在IFoo The compiler doesn't know that the variable foo happens to contain a instance of Foo ; 编译器不知道变量foo碰巧包含Foo的实例; it just looks at the type the variable is declared of. 它只是查看变量声明的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM