virtual 不能與 static 、 abstract 、 private 或 override 連用。
舉例如下
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();
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:class20.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */DoSomething 為 virtual 方法
public virtual void DoSomething() {
System.Console.WriteLine("There is no spoon.");
}子類別改寫可用 override 或 new 改寫
public override void DoSomething() {
System.Console.WriteLine("Free your mind.");
}override 或 new 改寫的方法,執行結果在 foreach 迴圈兩者會有差異。
編譯執行,結果如下

| 中英文術語對照 | |
|---|---|
| 方法 | method |
| 子類別 | subclass |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: virtual (C# 參考)
沒有留言:
張貼留言