期待「來自派生的問候」。但得到「從基地你好。」。爲什麼調用基類方法代替派生類方法?
class Program
{
interface IBase
{
void Method();
}
public class Base: IBase
{
public virtual void Method()
{
Console.WriteLine("Hello from the base.");
}
}
public class Derived : Base
{
public virtual new void Method()
{
Console.WriteLine("Hello from the derived.");
}
}
static void Main(string[] args)
{
IBase x = new Derived();
x.Method();
}
}
那麼,爲什麼不調用派生類的方法。更重要的是,我怎樣才能讓派生類的方法被調用,而不需要將x強制轉換爲派生類型?
在我的實際應用中,IBase有其他幾種相關的方法,派生只取代IBase中的兩種方法。
+10對於錯誤的解釋。 – 2012-11-13 15:35:39
建議您建議解決方案不可構建。編譯器抱怨「無法覆蓋成員'Program.Base.Method()',因爲它沒有被標記爲虛擬的,抽象的或者被覆蓋的。 – estimpson
基本方法必須標記爲'虛擬'並且派生方法'覆蓋' –