为什么使用sealed修饰符

如果基类(base class)B中定义了虚方法,而sealed class S从B类衍生。对于一个类型为S的名为s的变量调用虚方法的代码,编译器可以确信s一定是类型为S的。但是如果类S实际上没有被sealed,则这个变量s可能是类S的衍生类的实例而这个衍生类同时又重写(override)了该虚方法。这时为了正确性,编译器必须以虚方法调用的方式执行该代码。这比直接执行的成本要高。C#中string类型就用的类似方法,实例化时不用new关键字。
Class B
{}
sealed Class S
{virtual void Do(){...}}
s.Do();//如果S不是sealed的,那么s可能是S的衍生类的对象
如下:
Class S
{virtual void Do(){...}}
Class C
{override void Do(){...}}
C s=new C.C();/*这个s也是S类型的,从而编译器必须以虚方法调用的方式执行该代码。这比直接执行的成本要高。*/

另外一个例子是attribute属性类。有一个FxCop的规则(Avoid unsealed attributes)专门检查定义的属性类是不是sealed。除了上面谈及的原因,还特别提到Attribute.GetCustomAttributeAPI. 其解释如下:The .NET Framework class library provides methods for retrieving custom attributes. These methods search the attribute inheritance hierarchy by default; for example System.Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.

原文:http://forlan.bokee.com/3637173.html有些改动,请原谅

原文地址:https://www.cnblogs.com/68681395/p/1804802.html