C#的扩展方法precedence方法、precedence

由网友(浊清)分享简介:我有点困惑如何扩展方法工作。 I'm a bit confused about how extension methods work. 如果我读这正确的http://msdn.microsoft.com/en-us/library/bb383977.aspx这If扩展方法具有相同签名的密封类的方法,什么是调用pre...

我有点困惑如何扩展方法工作。

I'm a bit confused about how extension methods work.

如果我读这正确的http://msdn.microsoft.com/en-us/library/bb383977.aspx这If扩展方法具有相同签名的密封类的方法,什么是调用precedence?。

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?.

再下面应该写出来实例,而是把它写入扩展方法。

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();
    }
}

鸭preciate澄清行为的任何帮助。

Appreciate any help in clarifying the behavior.

推荐答案

这里最大的区别是,您已经定义了的IFoo 接口的扩展方法,你的变量的类型是的IFoo

The big difference here is that you have defined an extension method for the IFoo interface, and your foo variable is of type IFoo.

如果您的code是这样的:

If your code was to look like this:

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

在Foo.Say()方法将被执行,而不是扩展方法。

The Foo.Say() method would be executed, not the extension method.

我希望我可以给你,为什么这是一个彻底的解释,但我只能覆盖的基本机制。当你的变量是的IFoo 的类型不与,当编译器试图确定哪些方法可用,它看着过去的任何非接口方法美孚类(如它应该)。然而,扩展方法说()可用,所以调用此。

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). However, the extension method Say() was available, so it invoked this.

阅读全文

相关推荐

最新文章