我怎么可以继承String类?我怎么、String

2023-09-04 00:40:17 作者:我不喜欢放弃这个词

我要继承扩展C#string类中添加像 WORDCOUNT方法()和几个其他许多人,但我不断收到此错误:

I want to inherit to extend the C# string class to add methods like WordCount() and several many others but I keep getting this error:

错误1'WindowsFormsApplication2.myString':不能从密封的派生   类型字符串

Error 1 'WindowsFormsApplication2.myString': cannot derive from sealed type 'string'

有没有其他办法可以突破这个?我试着用字符串字符串,但没有奏效。

Is there any other way I can get past this ? I tried with string and String but it didn't work.

推荐答案

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

System.String is sealed, so, no, you can't do that.

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

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

使用:

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