Using Sealed Class in .NET
无意中看到个英文博客,说老实话还从来没尝试过阅读英文文章
今天居然“鼓起勇气”一口气看完,而且越看越顺,这位老师的用语感觉还是很简单的。。 我还挺高兴的。。
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once
a class is defined as sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET,
NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class,
compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
Why Sealed Classes?
We just saw how to create and use a sealed class. The main purpose of a sealed class to take away
the inheritance feature from the user so they cannot derive a class from a sealed class. One of
the best usage of sealed classes is when you have a class with static members. For example, the
Pens and Brushes classes of the System.Drawing namespace.
The Pens class represent the pens for standard colors. This class has only static members. For
example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents
standard brushes. The Brushes.Blue represents a brush with blue color.
So when you're designing your application, you may keep in mind that you have sealed classes to
seal user's boundaries.
为什么要用密封类?
我们只知道如何创建和使用密封类,主要的意图是避免这个类被继承
有一个很典型的密封类,比如System.Drawing吓得Pens类和Brushes类
Pens类代表一支笔的颜色,这个类只用一些静态属性
Pens,蓝色就代表这只笔是蓝色的
相同的
Brushes,蓝色就代表这个刷子是蓝色的
(自己的理解:刷子就是刷子,一个门是不可能来继承一个刷子的)
所以当你编写你的程序时,你可以记住你可以使用Sealed来约束用户的动作
他的博客地址是:http://www.c-sharpcorner.com/UploadFile/mahesh/SealedClasses11142005063733AM/SealedClasses.aspx
有兴趣的朋友也可以去看看哦