2017年9月6日 星期三

[C#] 繼承 範例 - virtual 、override 、base 用法


今天我們來試試看,


首先實體劃一個 testInher ,在這時候,我們會看到因為建構式的關係,
出現這兩個訊息
00 message of ExampleClass: in class ExampleClass()
01 message of inher(): in class inher : ExampleClass

接著,當我們呼叫 testInher.echoMsgInher(); 時候,
由於此方法在父 class 宣告為  public virtual void echoMsgInher()  ,有使用  virtual
故在繼承之後,需要 override 這個方法
此外,由於 base.echoMsgInher(); ,因此會執行父class 裡面的 方法內容

故 執行結果後,會出現
03 message in Father: echoMsgInher
04 message of son: in class inher : ExampleClass







using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
inher testInher = new inher();
testInher.echoMsgInher();
Console.Read();
}
}
class ExampleClass
{
public ExampleClass()
{
Console.WriteLine("00 message of ExampleClass: in class ExampleClass()");
}
public virtual void echoMsgInher()
{
Console.WriteLine("03 message in Father: echoMsgInher");
}
}
class inher : ExampleClass
{
public inher()
{
Console.WriteLine("01 message of inher(): in class inher : ExampleClass");
}
public override void echoMsgInher()
{
base.echoMsgInher();
Console.WriteLine("04 message of son: in class inher : ExampleClass");
}
}
}
//===================================================
// Result
//===================================================
//00 message of ExampleClass: in class ExampleClass()
//01 message of inher(): in class inher : ExampleClass
//03 message in Father: echoMsgInher
//04 message of son: in class inher : ExampleClass
view raw gistfile1.txt hosted with ❤ by GitHub
執行結果:
00 message of ExampleClass: in class ExampleClass()
01 message of inher(): in class inher : ExampleClass
03 message in Father: echoMsgInher
04 message of son: in class inher : ExampleClass

沒有留言:

張貼留言