C# 快速導覽 - virtual 成員

宣告為 virtual 的方法 (method) 可被子類別 (subclass) 改寫。



virtual 不能與 staticabstractprivateoverride 連用。


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


DoSomethingvirtual 方法
2
3
4
public virtual void DoSomething() {
    System.Console.WriteLine("There is no spoon.");
}


子類別改寫可用 overridenew 改寫
8
9
10
public override void DoSomething() {
    System.Console.WriteLine("Free your mind.");
}


overridenew 改寫的方法,執行結果在 foreach 迴圈兩者會有差異。


編譯執行,結果如下



中英文術語對照
方法method
子類別subclass


您可以繼續參考
類別


相關目錄
回 C# 快速導覽
回 C# 教材
回首頁


參考資料
Standard ECMA-334 C# Language Specification
msdn: virtual (C# 參考)

沒有留言: