0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】【文法】オーバーライド,is, asによるキャスト

Posted at

    // new, virtual - override, abstruct , is, as
    class Practice8_3
    {
        static void Main(string[] args)
        {
            Parent p = new Child();
            p.Show();
            p.Run();

            // Is - newしたクラスと一致するかどうか。
            if (p is Child)
            {

            }

            // As - ダウンキャストに失敗した場合,nullになる。
            // 通常のキャスト (ClassXX)ではキャスト失敗時に例外が発生する。
            var x = p as Sister;
        }
    }

    abstract class Parent
    {
        public void Show()
        {
            Console.WriteLine("parent");
        }

        // オーバーライドを許可
        public virtual void Run()
        {
            Console.WriteLine("親が走る。");
        }

        // オーバーライドを強制
        public abstract void Jump();
    }

    // sealedで継承不可にする。(javaでいうfinal)
    sealed class Child : Parent
    {
        // Overrideできない。(原則使用禁止。)
        public new void Show()
        {
            Console.WriteLine("child");
        }

        // Overrideが可能。(しなくてもよい)
        public override void Run()
        {
            Console.WriteLine("子が走る。");
        }

        // Overrideが必須。
        public override void Jump()
        {
            
        }
    }

    class Sister : Parent
    {
        public override void Jump()
        {
        }
    }

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?