我对扩展方法如何工作有点困惑。C#扩展方法优先
如果我正确阅读这个http://msdn.microsoft.com/en-us/library/bb383977.aspx和这If an extension method has the same signature as a method in the sealed class, what is the call precedence?。
然后下面应该写出“实例”,而是写入“扩展方法”。
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();
}
}
感谢任何帮助澄清行为。
你确定用扩展方法编译的内置方法重写吗? – kenny
乍一看或编译它时,界面没有Say(),所以你所称的扩展方法。在接口中使用Save()时,编译器会抱怨'C:\ projects \ _play \ ExtensionMethods \ Program.cs(2,1):错误CS0116:名称空间不能直接包含成员,如字段或方法' – kenny