bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

C#のsealedを使ってみる

C#をそれなりに使うようになったが幾つかの機能を使ったことがない。
sealedもその一つ。
派生クラスで関数をoverrideすることで処理内容を変えることができるが、
それを禁止することができる。
sealedが付いた関数を派生クラスでoverrideするとコンパイル時エラーになる。
override禁止の意図を明確にできるので、チームメンバーに変更するなというメッセージを伝えることができる。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    /// <summary>
    /// 基底クラス.
    /// </summary>
    public class A
    {
        public virtual void DoSomething()
        {
            Console.WriteLine("class A.DoSomething");
        }
    }

    /// <summary>
    /// 継承用の抽象クラス.
    /// </summary>
    public abstract class B : A
    {
        public abstract override void DoSomething();
    }

    /// <summary>
    /// 新しい実装の派生クラス.
    /// </summary>
    public class C : B
    {
        public override void DoSomething()
        {
            Console.WriteLine("class C.DoSomething");
        }
    }

    /// <summary>
    /// DoSomethingのoverrideを禁止した派生クラス
    /// </summary>
    public class D : B
    {
        public sealed override void DoSomething()
        {
            Console.WriteLine("class D.DoSomething with sealed");
        }
    }

    /// <summary>
    /// DoSomethingのoverrideを禁止された派生クラス
    /// </summary>
    public class E : D
    {
        /* DoSomethingは禁止されているのでビルドエラー.
        public override void DoSomething()
        {
            Console.WriteLine("class E.DoSomething");
        }
        */
    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.DoSomething();

            // build error.
            //B b = new B();
            //b.DoSomething();

            B c = new C();
            c.DoSomething();

            // Exception.
            //D d = new D();
            //d.DoSomething();

            B e = new E();
            e.DoSomething();

            Console.ReadLine();
        }
    }
}