c# sealed

在类声明中使用sealed可防止其它类继承此类;在方法声明中使用sealed修饰符可防止扩充类重写此方法。
sealed修饰符主要用于防止非有意的派生,但是它还能促使某些运行时优化。具体说来,由于密封类永远不会有任何派生类,所以对密封类的实例的虚拟函数成员的调用可以转换为非虚拟调用来处理。

密封类:
密封类在声明中使用sealed 修饰符,这样就可以防止该类被其它类继承。如果试图将一个密封类作为其它类的基类,C#将提示出错。理所当然,密封类不能同时又是抽象类,因为抽象总是希望被继承的。

在哪些场合下使用密封类呢?实际上,密封类中不可能有派生类。如果密封类实例中存在虚成员函数,该成员函数可以转化为非虚的,函数修饰符virtual 不再生效。

----------------------------------------------------------------

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

namespace @sealed
{
    class WithoutSealed
    { 
        public static void OutPut()
        {
            Console.WriteLine("i have not use sealed");
            Console.ReadLine();
        }
    }

    sealed class WithSealed
    {
        public static void OutPut()
        {
            Console.WriteLine("i have used sealed");
            Console.ReadLine();
        }
    }

    class WantInheriting : WithoutSealed //WithSealed it will be wrong
    {
        public new void OutPut()
        {
            Console.WriteLine("i have not use sealed and i am new");
            Console.ReadLine();
        }
    }


    class Program
    {

        static void Main(string[] args)
        {
            WithoutSealed.OutPut();
            WantInheriting WI = new WantInheriting();
            WI.OutPut();
        }
    }
}

 

posted @ 2012-04-21 11:35  sidihu  阅读(2242)  评论(0编辑  收藏  举报