Nas*_*ine 20 .net c# string inheritance
我想继承扩展C#字符串类来添加类似的方法WordCount()和其他许多方法,但我不断收到此错误:
错误1'WindowsFormsApplication2.myString':无法从密封类型'string'派生
有没有其他方法可以通过这个?我尝试过string,String但它没有用.
小智 72
另一种选择可能是使用隐式运算符.
例:
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) { }
}
Joh*_*ers 37
System.String是密封的,所以,不,你不能这样做.
您可以创建扩展方法.例如,
public static class MyStringExtensions
{
    public static int WordCount(this string inputString) { ... }
}
使用:
string someString = "Two Words";
int numberOfWords = someString.WordCount();
Con*_*ngo 11
如果您继承字符串类后的意图是简单地为字符串类创建别名,那么您的代码更自我描述,那么您就不能从字符串继承.相反,使用这样的东西:
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)
    {
    }
}