如何继承字符串类?

本文关键字:字符串 继承 何继承 | 更新日期: 2023-09-27 18:16:54

我想继承扩展c#字符串类,以添加方法,如WordCount()和其他几个,但我一直得到这个错误:

错误1 'WindowsFormsApplication2。myString':不能从sealed派生类型"字符串"

还有别的办法可以让我过去吗?我尝试了stringString,但它没有工作。

如何继承字符串类?

另一种选择是使用隐式操作符。

的例子:

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) { }
}

系统。字符串是密封的,所以,不,你不能这样做

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

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

使用:

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

如果您从string类继承的目的是简单地创建一个string类的别名,这样您的代码就更具有自描述性,那么您就不能从string类继承。相反,你可以这样写:

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

这意味着你的代码现在是更自我描述的,并且意图更清晰,例如:

Tuple<DictKey, DictValue, MetaData, SecurityString> moreDescriptive;

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

Tuple<string, string, string, string> lessDescriptive;

这种用于更多自描述代码的混叠方法也适用于字典、哈希集等。

当然,如果您的目的是向字符串类添加功能,那么最好的选择是使用扩展方法。

不能从字符串派生,但可以添加扩展,如:

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

helper类有什么问题?正如您的错误消息告诉您的那样,String是密封的,因此您当前的方法将不起作用。扩展方法是你的朋友:

myString.WordCount();

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

您不能继承密封类(这就是它的全部要点)和它不能同时用于string和System的原因。字符串是关键字string只是System.String的别名。

如果你不需要访问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;
    }
}

你仍然不能访问字符串类的私有方法和属性,但在我看来,这比这样写要好:

StringHelper.WordCount(yourString);

字符串类被标记为sealed,因为您不应该从它继承。

你能做的就是在别处实现这些函数。或者作为其他类的普通静态方法,或者作为扩展方法,使它们看起来像字符串成员。