mti*_*ijn 2 .net c# extension-methods
在下面的代码中,我定义了一个接口,一个抽象基类,一个打印"foo"的方法,一个实现这两个的类,一个接口上的扩展方法,其签名等于抽象基类中打印的方法"酒吧".当我运行这个样本时,为什么打印"bar"而不是"foo"?如果适用,这种语言设计选择背后的士气是什么?
public interface ISomething
{}
public abstract class SomethingElse
{
public void foo()
{
Console.WriteLine("foo");
}
}
public class DefinitelySomething : SomethingElse, ISomething
{}
public static class ISomethingExtensions
{
public static void foo(this ISomething graphic)
{
Console.WriteLine("bar");
}
}
class Program
{
static void Main(string[] args)
{
ISomething g = new DefinitelySomething();
g.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
因为变量声明为ISomething
.
实例方法直到运行时才知道,但方法重载解析是在编译时.无法保证实例实际上有合适的方法.在你的特定例子中,它具有但从类型安全角度来看是无关紧要的巧合.该行的重要类型g.foo()
是g被声明为不是运行时类型的类型