C#密封方法

iamzxf發表於2015-04-08

      如果不想一個類或方法再被繼承,可以在類或方法前加關鍵字sealed,禁止該方法被繼承。

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

namespace chap4_6
{
    class first
    {
        public virtual void F()
        {
            Console.WriteLine("first.F");
        }
        public virtual void G()
        {
            Console.WriteLine("first.G");
        }
    }

    class second : first
    {
        public sealed override void F()
        {
            Console.WriteLine("second.F");
        }
        public override void G()
        {
            Console.WriteLine("second.G");
        }
    }

    class third : second {
        /*sealed override void F()
        {
            Console.WriteLine("third.F");
        }*/
        public override void G()
        {
            Console.WriteLine("third.G");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            third th =new third();
            th.F();
            th.G();
            Console.ReadLine();
        }
    }
}

輸出結果:

second.F

third.G


相關文章