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.(…)

转载于:https://www.cnblogs.com/wangguangxin/p/4011969.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值