C#的扩展方法precedence [英] C# Extension method precedence

查看:250
本文介绍了C#的扩展方法precedence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我读这正确的<一个href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">http://msdn.microsoft.com/en-us/library/bb383977.aspx这<一href="http://stackoverflow.com/questions/2303885/if-an-extension-method-has-the-same-signature-as-a-method-in-the-sealed-class-wh">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.

这篇关于C#的扩展方法precedence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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