字符串是c#中的密封类型,因此无法派生自。你同意吗? [英] String is a sealed type in c# and hence cannot be derived from. Do you agree?

查看:570
本文介绍了字符串是c#中的密封类型,因此无法派生自。你同意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String是c#中的密封类型,因此无法派生。你是否b $ b同意?

解决方案

是: MSDN [ ^ ]


您无法从字符串派生 [ ^ ]。如你所说它是密封的。

但是,通过使用扩展方法,你实际上可以解决为字符串类添加更多功能。 / blockquote>

如果您确定需要扩展字符串的某些功能,那么扩展方法是字符串类的一个很好的选择。 />


继承经常被滥用,特别是在没有密封概念的C ++中。如果你正在开发一个类 X ,请确保它 X是一个字符串,而不是 X是用字符串实现的的。将客户端代码X紧密耦合到字符串可能会导致问题。密封关键字实际上是对此的保护。通常,它是从较低级别类派生业务类的有用保护。商务课程几乎总是低级课程来实施。



我会诚实地说这只是最近在C ++开发的背景下向我指出,但我会说这同样适用于大多数语言。继承是类之间最强大的关系之一,可以形成如Herb Sutter所指出的那样:继承的使用和滥用 [ ^ ]。同样,C ++引用,但可能与此问题相关。


String is a sealed type in c# and hence cannot be derived from. Do you
agree?

解决方案

Yes: MSDN[^]


You cannot derive from the string class[^]. As you mentioned it is sealed.
However, by using extension methods, you can actually work around to add more functionality to the string class.


If you are sure you need to extend some functionality of string, then extension methods are a good option for the string class.

Inheritance is often abused, especially in C++ which doesn''t have a concept of sealed. If you are developing a class X, be very sure that it X is a string, rather than X is implemented in terms of string. The tight coupling of client code of X to string can cause problems down the road. The sealed keyword is actually a safeguard against this. More often than not it is a useful protection from deriving business classes from lower level classes. Business classes are almost always implemented in terms of lower level classes.

I''ll be honest and say this is something that was only recently pointed out to me in the context of C++ development, but I would say the same applies to most languages. Inheritence is one of the most strongest relationship between classes that one can form as pointed out be Herb Sutter: Uses and Abuses of Inheritance[^]. Again, C++ references, but probably relevant to this question.


这篇关于字符串是c#中的密封类型,因此无法派生自。你同意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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