Sealed Class in C#

如果你不希望一个类被继承,那么可以把这个类声明为sealed类。

除此之外,声明为sealed类还会带来如下好处

1. 提高函数调用效率

JIT(Just in Time)编译器会优化sealed类的函数调用。

比如,如果从一个sealed class的实例上调用一个virtual method,那么就会把这次调用变成是non-virtual.

 

2. 更好的type safe保证

interface IInterface
{
}

class MyClass
{
}

class Program
{
	static void Main(string[] args)
	{
		MyClass instance = new MyClass();
		IInterface impl = (IInterface)instance;
	}
}

上面的代码并不会编译出错,虽然MyClass并没有实现IInterface接口。这是因为,instance可能是MyClass的某个子类,而该子类实现了IInterface接口。

 

如果我们把MyClass声明为Sealed类

interface IInterface
{
}

sealed class MyClass
{
}

class Program
{
	static void Main(string[] args)
	{
		MyClass instance = new MyClass();
		IInterface impl = (IInterface)instance;
	}
}

就会出现编译错误。

CLR via C#有一段关于sealed类的观点

When defining a new type, compilers should make the class sealed by default so that the class cannot be used as a base class. Instead, many compilers, including C#, default to unsealed classes and allow the programmer to explicitly mark aclass as sealed by using the sealed keyword. Obviously, it is too late now, but I think that today’s compilers have chosen the wrong default and it would be nice if it could change with future compilers. There are three reasons why a sealed class is better than an unsealed class:

  • Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
  • Performance: (…) if the JIT compiler sees a
    call to a virtual method using a sealed types, the JIT compiler can
    produce more efficient code by calling the method non-virtually.(…)
  • Security and Predictability:
    A class must protect its own state and not allow itself to ever become
    corrupted. When a class is unsealed, a derived class can access and
    manipulate the base class’s state if any data fields or methods that
    internally manipulate fields are accessible and not private.(…)
posted @ 2014-10-08 20:13  胸大无痣  阅读(450)  评论(0编辑  收藏  举报