2015/01/31

C#.Net Sealed

Sealed:可以防止其他類別繼承,也能避免方法被覆寫


Code:
using System;
using System.Windows.Forms;

namespace Sample
{
    public partial class Form1 : Form
    {
        class A
        {
            protected internal virtual void OutA()
            {
                Console.WriteLine("AA");
            }

            protected internal virtual void OutB()
            {
                Console.WriteLine("AB");
            }
        }


        class B : A
        {

            protected internal override void OutA()
            {
                Console.WriteLine("BA");
            }


            sealed protected internal override void OutB()
            {
                Console.WriteLine("BB");
            }

        }

        sealed class C : B
        {
            protected internal override void OutA()
            {
                Console.WriteLine("CA");
            }
        }


        public Form1()
        {
            
            new A().OutA();
            new A().OutB();

            new B().OutA();
            new B().OutB();

            new C().OutA();
            new C().OutB();
        }

    }

}



執行結果: