我怎样才能inheritance字符串类?

我想inheritance扩展C#字符串类来添加像WordCount()和其他几个方法,但我不断收到此错误:

错误1’WindowsFormsApplication2.myString’:无法从密封类型’string’派生

有没有其他方法可以通过这个? 我尝试使用stringString但它没有用。

System.String是密封的,所以,不,你不能这样做。

您可以创建扩展方法 。 例如,

 public static class MyStringExtensions { public static int WordCount(this string inputString) { ... } } 

使用:

 string someString = "Two Words"; int numberOfWords = someString.WordCount(); 

另一种选择可能是使用隐式运算符。

例:

 class Foo { readonly string _value; public Foo(string value) { this._value = value; } public static implicit operator string(Foo d) { return d._value; } public static implicit operator Foo(string d) { return new Foo(d); } } 

Foo类就像一个字符串。

 class Example { public void Test() { Foo test = "test"; Do(test); } public void Do(string something) { } } 

如果您inheritance字符串类后的意图是简单地为字符串类创建别名 ,那么您的代码更自编,那么您就不能从字符串inheritance。 相反,使用这样的东西:

 using DictKey = System.String; using DictValue= System.String; using MetaData = System.String; using SecurityString = System.String; 

这意味着您的代码现在更加自我描述,意图更清晰,例如:

 Tuple moreDescriptive; 

在我看来,与相同的代码相比,此代码显示更多的意图,没有别名:

 Tuple lessDescriptive; 

这种用于更多自描述代码别名方法也适用于字典,散列集等。

当然,如果您的目的是为字符串类添加function,那么最好的办法是使用扩展方法。

您无法从字符串派生,但您可以添加以下扩展名:

 public static class StringExtensions { public static int WordCount(this string str) { } } 

助手class有什么问题? 正如您的错误消息告诉您的那样,String已被密封 ,因此您当前的方法将无效。 扩展方法是你的朋友:

 myString.WordCount(); static class StringEx { public static int WordCount(this string s) { //implementation. } } 

你不能inheritance一个密封的类(这是它的全部要点)以及它不能同时使用string和System.String的原因是关键字string只是System.String的别名。

如果您不需要访问字符串类的内部,那么您可以创建一个Extension Method ,在您的情况下:

 //note that extension methods can only be declared in a static class static public class StringExtension { static public int WordCount(this string other){ //count the word here return YOUR_WORD_COUNT; } } 

您仍然无法访问字符串类的私有方法和属性,但IMO比写入更好:

 StringHelper.WordCount(yourString); 

这也是LINQ的工作方式。

您是否认为sealed关键字不仅仅是为了好玩? 字符串类标记为sealed 因为您不应该inheritance它

所以不,你不能“绕过它”。

可以做的是在别处实现这些function。 无论是作为其他类的普通静态方法,还是作为扩展方法 ,都允许它们看起来像字符串成员。

但是当一个类被标记为密封时,你不能“绕过”它。