舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Demo { public void DoSomething() { System.Console.WriteLine( "There is no spoon." ); } } class Demo2 : Demo { public new void DoSomething() { System.Console.WriteLine( "Free your mind." ); } } class DemoTest { static void Main() { Demo2 d = new Demo2(); d.DoSomething(); } } /* 《程式語言教學誌》的範例程式 檔名:class14.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
Demo2 改寫了 Demo 的 DoSomething()
8 9 10 | public new void DoSomething() { System.Console.WriteLine( "Free your mind." ); } |
編譯執行,結果如下

如果子類別除了改寫外,還需要先執行父類別定義的部份,可用關鍵字 base 先呼叫父類別的方法,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Demo { public void DoSomething() { System.Console.WriteLine( "There is no spoon." ); } } class Demo2 : Demo { public new void DoSomething() { base .DoSomething(); System.Console.WriteLine( "Free your mind." ); } } class DemoTest { static void Main() { Demo2 d = new Demo2(); d.DoSomething(); } } /* 《程式語言教學誌》的範例程式 檔名:class15.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
通常 base 會放在改寫方法的第 1 行
9 10 11 12 | public new void DoSomething() { base .DoSomething(); System.Console.WriteLine( "Free your mind." ); } |
編譯執行,結果如下

中英文術語對照 | |
---|---|
子類別 | subclass |
父類別 | superclass |
方法 | method |
關鍵字 | keyword |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 繼承 (C# 程式設計手冊)
msdn: new 修飾詞 (C# 參考)
沒有留言:
張貼留言