請看下面的代碼:擴展方法VS父類的方法行爲
class A
{
public string DoSomething(string str)
{
return "A.DoSomething: " + str;
}
}
class B : A
{
}
static class BExtensions
{
public static string DoSomething(this B b, string str)
{
return "BExtensions.DoSomething: " + str;
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
var b = new B();
Console.WriteLine(a.DoSomething("test"));
Console.WriteLine(b.DoSomething("test"));
Console.ReadKey();
}
}
代碼的輸出是:
A.DoSomething:測試
A.DoSomething:測試
當它編譯它不給予警告。
我的問題是:爲什麼在代碼編譯時沒有警告,調用DoSomething
方法時會發生什麼?
[這涉及到這個問題](http://stackoverflow.com/questions/ 1745166/override-or-shadow-a-method-with-extension-method)和[also this](http://stackoverflow.com/questions/899539/is-there-any-way-in-c-to -override-a-class-method-with-an-extension-method) – 2010-02-04 11:40:31