「C#」overrideとvirtualでメソッドのオーバーライドを実装するサンプル

書式
親クラスのメソッド virtual
子クラスのメソッド override

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 親クラス
class ParementClass
{
public virtual string showMsg()
{
return "parent class method AAA";
}
}
// 子クラス
class ChildRenClass : ParementClass
{
  // オーバーライド
public override string showMsg()
{
return "child class method BBB";
}
}
class DemoOne
{
static void Main()
{
   // 子クラスのインスタンス
ParementClass cft = new ChildRenClass();
Console.WriteLine(cft.showMsg());
}
}
// 親クラス class ParementClass { public virtual string showMsg() { return "parent class method AAA"; } } // 子クラス class ChildRenClass : ParementClass {   // オーバーライド public override string showMsg() { return "child class method BBB"; } } class DemoOne { static void Main() {    // 子クラスのインスタンス ParementClass cft = new ChildRenClass(); Console.WriteLine(cft.showMsg()); } }
// 親クラス
class ParementClass
{
    public virtual string showMsg()
    {
        return "parent class method AAA";
    }
}
// 子クラス
class ChildRenClass : ParementClass
{
  // オーバーライド
    public override string showMsg()
    {
        return "child class method BBB";
    }
}
class DemoOne
{
    static void Main()
    {
         // 子クラスのインスタンス
        ParementClass cft = new ChildRenClass();

        Console.WriteLine(cft.showMsg()); 
    }
}

結果
child class method BBBBBB

C#

Posted by arkgame