为何“密封”的关键字在.net中存在吗? [英] Why does the 'sealed' keyword exist in .Net?

查看:114
本文介绍了为何“密封”的关键字在.net中存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个大量的类在.NET Framework中被继承这些类用自己的标记为密封,preventing你。这无疑违背了面向对象的,在那里你可以扩展和重新定义现有对象的行为的性质。

有一个很好的理由为密封的关键字的存在?

  

作为一个例子,   在NotifyCollectionChangedEventArgs   Silverlight中被密封。我想   创建我自己的版本   的ObservableCollection的支持   的AddRange和RemoveRange,但   NCCEA Silverlight的版本不   提供一个支持的构造   多个项目的NewItems和   OldItems属性,这是已经被定义为ILists。通常情况下,我只希望   用我自己的变体扩展类   这推翻了NewItems和   OldItems性能,但在这种情况   我不能,我看不出有任何理由   这应该是这样的。

解决方案

设计类(或框架)是可扩展是不平凡的,并把简单的继承不是面向对象编程的一个原则。

所以密封的存在是为了让开发者/设计师EX preSS和preserve这些意图。密封类也可以通过减少维护的负担他们的生活更轻松。它允许原开发商来控制类(或框架)的扩展,这样他们就可以进行内部的变化,而不必担心破坏的修改给别人code。

一个原则是,开发人员应该封住的类的默认。然后,当开发人员创建一个非密封类有意的,它迫使他们思考的可扩展性。


参考:埃里克利珀 - 为什么是这么多框架类密封?

A large number of classes in the .Net framework are marked as 'sealed', preventing you from inheriting those classes with your own. Surely this goes against the nature of object orientation, where you can extend and redefine the behaviour of existing objects.

Is there a good reason for the existence of the 'sealed' keyword?

As an example, NotifyCollectionChangedEventArgs in Silverlight is sealed. I wanted to create my own version of ObservableCollection that supported AddRange and RemoveRange, but the Silverlight version of NCCEA doesn't provide a constructor that supports multiple items for the NewItems and OldItems properties, which are already defined as ILists. Usually, I'd just extend the class with my own variant that overrode the NewItems and OldItems properties, but in this case I can't and I can see no reason why that should be the case.

解决方案

Designing classes (or frameworks) to be extensible isn't trivial, and put simply inheritance is not the single principle of Object Oriented programming.

So sealed exists to allow the developer / designer to express and preserve those intentions. Sealing a class can also make their life easier by reducing the maintenance burden. It allows the original developer to control how the class (or framework) is extended, so they can make internal changes without worrying about breaking changes to others code.

One principle is that developers should seal any leaf classes by default. Then, when the developer creates an unsealed class intentionally, it forces them to think about extensibility.


Ref: Eric Lippert - Why Are So Many Of The Framework Classes Sealed?

这篇关于为何“密封”的关键字在.net中存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆