在C#中,override
關(guān)鍵字用于重寫父類中的虛方法。通過在子類中使用override
關(guān)鍵字來標(biāo)記方法,可以覆蓋父類中已經(jīng)存在的虛方法,使得在運(yùn)行時調(diào)用子類對象的該方法時,實(shí)際執(zhí)行的是子類中重寫的方法,而不是父類中的方法。這樣可以實(shí)現(xiàn)多態(tài)性,使得程序能夠根據(jù)實(shí)際的對象類型來決定調(diào)用的方法。
示例代碼如下所示:
class BaseClass
{
public virtual void Print()
{
Console.WriteLine("BaseClass Print method");
}
}
class DerivedClass : BaseClass
{
public override void Print()
{
Console.WriteLine("DerivedClass Print method");
}
}
class Program
{
static void Main()
{
BaseClass obj = new DerivedClass();
obj.Print(); // 輸出:DerivedClass Print method
}
}