學一點記一點,免得忘記..
Father
代碼
class Father
{
/// <summary>
/// 虛方法可以被派生重寫
/// 其實就是父親告訴兒子,這項技能你可以學,但是學了就需要有自己的“創新(override or new)”
/// </summary>
public virtual void virtualMethod()
{
Console.WriteLine("Father Virtual Method");
}
/// <summary>
/// 如果在衍生類別中有同名方法,可以拿new關鍵字,隱藏父類方法,當然new也可以用於執行個體化類
/// 其實可以理解為兒子學會了和父親“類似”的技能,比如父親唱通俗哥,兒子唱流行歌
/// </summary>
public void newMethod()
{
Console.WriteLine("Father New Method");
}
/// <summary>
/// 衍生類別不能繼承
/// 其實可以理解為父親不希望兒子學會的,比如父親搶劫,不希望兒子學會...
/// </summary>
private void privateMethod()
{
Console.WriteLine("Father Private Method");
}
/// <summary>
/// 衍生類別可以繼承
/// 其實可以理解為父親遺傳給兒子的技能
/// </summary>
public void publicMethod()
{
Console.WriteLine("Father Public Method");
}
/// <summary>
/// publicMethod的重載
/// 重載:同名不同參
/// 也是父親遺傳給兒子的技能
/// </summary>
public void publicMethod(string message)
{
Console.WriteLine("Father Public Method" + message);
}
}
Son
代碼
class Son : Father
{
/// <summary>
/// 重寫基類的虛方法
/// 其實可以理解為兒子學會了父親的技能,並且有了自主智慧財產權
/// </summary>
public override void virtualMethod()
{
Console.WriteLine("Son Virtual Method");
}
/// <summary>
/// 隱藏父類的重名方法
/// 其實可以理解為兒子學會了父親的技能,並且有了自主智慧財產權
/// </summary>
public new void newMethod()
{
Console.WriteLine("Son New Method");
}
}
Main
代碼
class Program
{
static void Main(string[] args)
{
Son son = new Son();
son.virtualMethod();
son.newMethod();
son.publicMethod();
Console.WriteLine();
Father father = new Father();
father.virtualMethod();
father.newMethod();
father.publicMethod();
Console.WriteLine();
Father father_son = new Son();
father_son.virtualMethod();//override完全重寫的基類的方法
father_son.newMethod();//new僅僅是隱藏了,當出現上轉型對象時,還是調用父親的方法
father_son.publicMethod();
}
}
輸出
Son Virtual Method
Son New Method
Father Public Method
Father Virtual Method
Father New Method
Father Public Method
Son Virtual Method
Father New Method
Father Public Method