using system;
using system.collections.generic;
using system.linq;
using system.text;
#region 概述
//在类声明中使用sealed可防止其它类继承此类;在方法声明中使用sealed修饰符可防止扩充类重写此方法。
//sealed修饰符主要用于防止非有意的派生,但是它还能促使某些运行时优化。具体说来,由于密封类永远不会有任何派生类,所以对密封类的实例的虚拟函数成员的调用可以转换为非虚拟调用来处理。
//密封类://密封类在声明中使用sealed 修饰符,这样就可以防止该类被其它类继承。如果试图将一个密封类作为其它类的基类,c#将提示出错。理所当然,密封类不能同时又是抽象类,因为抽象总是希望被继承的。//在哪些场合下使用密封类呢?实际上,密封类中不可能有派生类。如果密封类实例中存在虚成员函数,该成员函数可以转化为非虚的,函数修饰符virtual 不再生效。#endregionnamespace sealed密封类
{ class nosealed
{ public static void oo()
{
console.writeline(没有使用密封);
}
}
sealed class yessealed
{ public static void oo()
{
console.writeline(使用了密封);
}
} class myclass : nosealed //yessealed 那就错了
{ public new void oo()
{
console.writeline(没有继承密封);
}
} //密封类不可以被继承,可以被调用
sealed class mysealed //声明为密封类
{ public int x; public int y;
} class program
{ static void main(string[] args)
{
nosealed.oo();
myclass m = new myclass();
m.oo(); //调用密封类
yessealed.oo();
mysealed m = new mysealed();
m.x = 100;
m.y = 200;
console.writeline(x={0}, y = {1}, m.x, m.y);
console.readline();
console.readkey();
}
}
}