Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class A {
// 表示可以讓衍生類別覆寫方法主體
public virtual void PrintClassName() {
Console.WriteLine( "This is A" );
}
// 沒有 virtual,衍生類別不可覆寫
public void DoSomethingElse() {
Console.WriteLine( "Does Something" );
}
}
class B : A {
// 因為要覆寫原本的 virtual 方法,因此使用 override 修飾詞
public override void PrintClassName() {
Console.WriteLine( "This is B, which is [derived/inherited] from A" );
}
// 只要基底類別沒有此方法名稱,都可以繼續定義新的 virtual 方法
// 當然基底類別看不到這個方法
public virtual void DoSomethingElse() {
Console.WriteLine( "B Does Something Else" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment