如果你希望确保一个类不被作为基类使用,那么就在定义这个类时使用sealed关键字.唯一的限制是抽象类不能作为封闭的类使用,因为抽象类的本质决定它们必须被作为基类使用.封闭类的用途是防止意外的派生操作,但将类定义为封闭的也会启用某些运行时优化功能.具体的说,因为编译器确定这个类没有任何派生类,所以可以将封闭类实例上的虚拟函数成员调用转换为非虚拟调用.下面是一个封闭类的例子:
using System;
sealed class Point
{
public Point(int x,int y)
{
X=x;
Y=y;
}
public int X;
public int Y;
}
/*
Uncommenting this class and attempting to build the application will result in a compiler error ,as sealed classes cannot be derived from.
class MyPoint:Point
{]
*/
class SealedApp
{
public static void Main()
{
point pt=new Point(6,16);
Console.WriteLine("x-{0},y={1}",pt.X,pt.Y);
}
}