c# - 如何继承字符串类?

标签 c# .net string inheritance

我想继承以扩展 C# 字符串类以添加方法,如 WordCount() 和许多其他方法,但我不断收到此错误:

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

还有其他方法可以解决这个问题吗?我尝试使用 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) { }
}

关于c# - 如何继承字符串类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8388964/

相关文章:

c++ - 在 C++ 中使用字符串//我该怎么做?

r - 从 R 中的字符串中提取字母

c# - 如何使用 Visual Studio 2008 部署 asp.net 应用程序

c# - 如何跟踪鼠标 X/Y 位置并将其打印到标签上?

C#时区计算问题

c# - 试图将 IList 转换为 List 以便 AddRange

c# - 如何使用 config c# 中的规则在 NLog 中发送特定功能

c# - 是否可以在 DebuggerDisplay 中使用条件?

java - Java 中的 HMAC-SHA256/从 C# 翻译

python - Python 分隔连续字符串