C#關(guān)鍵字之覆寫overwrite介紹
一、簡介
overwrite覆寫,用new實(shí)現(xiàn)。在子類中用 new 關(guān)鍵字修飾定義的與父類中同名的方法,也稱為覆蓋,覆蓋不會(huì)改變父類方法的功能。
二、代碼
namespace 重寫
{
class Parent
{
public void F()
{
Console.WriteLine("Parent.F()");
}
//重寫的屬性必須是virtual、abstract或override
public virtual void G() //虛方法
{
Console.WriteLine("Parent.G()");
}
}
class ChildOne : Parent //子類一繼承父類
{
new public void F() //覆寫(overwrite)父類函數(shù)
{
Console.WriteLine("ChildOne.F()");
}
public override void G() //重寫(override)父類虛函數(shù),主要實(shí)現(xiàn)多態(tài)
{
Console.WriteLine("ChildOne.G()");
}
}
class ChildTwo : Parent //子類二繼承父類
{
new public void F()
{
Console.WriteLine("ChildTwo.F()");
}
public override void G()
{
Console.WriteLine("ChildTwo.G()");
}
}
class Program
{
static void Main(string[] args)
{
Parent childOne = new ChildOne();
Parent childTwo = new ChildTwo();
//調(diào)用Parent.F()
childOne.F();
childTwo.F();
//實(shí)現(xiàn)多態(tài)
childOne.G();
childTwo.G();
}
}
}三、結(jié)果
重寫子類的方法,但是不會(huì)覆蓋父類的方法。

到此這篇關(guān)于C#關(guān)鍵字之覆寫overwrite的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#提取網(wǎng)頁中超鏈接link和text部分的方法
這篇文章主要介紹了C#提取網(wǎng)頁中超鏈接link和text部分的方法,涉及C#正則表達(dá)式及字符串操作相關(guān)技巧,需要的朋友可以參考下2016-02-02
C# 使用 GDI+ 實(shí)現(xiàn)添加中心旋轉(zhuǎn)(任意角度)的文字
這篇文章主要介紹了C# 使用 GDI+ 實(shí)現(xiàn)添加中心旋轉(zhuǎn)(任意角度)的文字,需要的朋友可以參考下2018-04-04
c#實(shí)現(xiàn)網(wǎng)站監(jiān)控查看是否正常示例
這篇文章主要介紹了使用c#監(jiān)控網(wǎng)站是否正常的功能示例,大家參考使用吧2014-01-01
C# 利用AForge實(shí)現(xiàn)攝像頭信息采集
這篇文章主要介紹了C# 如何利用AForge實(shí)現(xiàn)攝像頭信息采集,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07
C#中靜態(tài)方法和實(shí)例化方法的區(qū)別、使用
這篇文章主要介紹了C#中靜態(tài)方法和實(shí)例化方法的區(qū)別、使用,文中講解的非常細(xì)致,對(duì)大家的學(xué)習(xí)有所幫助,感興趣的朋友可以了解下2020-06-06

