我想继承以扩展 C# 字符串类以添加方法,如 WordCount()
和许多其他方法,但我不断收到此错误:
Error 1 'WindowsFormsApplication2.myString': cannot derive from sealed type 'string'
还有其他方法可以解决这个问题吗?我尝试使用 string
和 String
但它没有用。
最佳答案
另一种选择是使用隐式运算符。
例子:
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/