我怎样才能继承字符串类?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Foo类就像一个字符串.

class Example {
    public void Test() {
        Foo test = "test";
        Do(test);
    }
    public void Do(string something) { }
}
Run Code Online (Sandbox Code Playgroud)

  • "return d.ToString()"需要实现ToString()或返回classname.认为它应该返回d._value.有点偏离但有趣的是,如果该示例用于激发在类中存储多个类型对象,并且实现了更多运算符来处理与外部世界的实际数据类型的交换.注意"d"引用类本身,d._value引用存储值.如果没有实现ToString(),我们将获得返回类名的默认实现. (5认同)
  • 出色的解决方案。然后,您可以为构造添加验证、一些 `==`、`!=` 运算符、`Equals` 和 `GetHashCode` 方法,并且您有一个甜蜜的封装值对象。我只是使用了上面的解决方案,以及上面提到的其他成员,效果很好。 (2认同)
  • @Omzig,对,应该是`return d._value;`。 (2认同)
  • 我喜欢这个解决方案。使用这种方法,我可以定义自己的“字符串类”,它在日常使用中充当字符串,但同时也是类型安全的,因此编译器将阻止我将 Foo1 变量分配给 Foo2 变量,即使它们都是字符串。 (2认同)

Joh*_*ers 37

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

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

public static class MyStringExtensions
{
    public static int WordCount(this string inputString) { ... }
}
Run Code Online (Sandbox Code Playgroud)

使用:

string someString = "Two Words";
int numberOfWords = someString.WordCount();
Run Code Online (Sandbox Code Playgroud)

  • 如果您不知道[扩展方法](http://msdn.microsoft.com/en-us/library/bb383977.aspx)是什么(我没有),那么该页面是一个很好的资源. (5认同)

Con*_*ngo 11

如果您继承字符串类后的意图是简单地为字符串类创建别名,那么您的代码更自我描述,那么您就不能从字符串继承.相反,使用这样的东西:

using DictKey = System.String;
using DictValue= System.String;
using MetaData = System.String;
using SecurityString = System.String;
Run Code Online (Sandbox Code Playgroud)

这意味着您的代码现在更加自我描述,意图更清晰,例如:

Tuple<DictKey, DictValue, MetaData, SecurityString> moreDescriptive;
Run Code Online (Sandbox Code Playgroud)

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

Tuple<string, string, string, string> lessDescriptive;
Run Code Online (Sandbox Code Playgroud)

这种用于更多自描述代码别名方法也适用于字典,散列集等.

当然,如果您的目的是为字符串类添加功能,那么最好的办法是使用扩展方法.

  • 我喜欢你的答案,但不幸的是,这个问题不是真的:P (4认同)
  • 使用 C# 元组类型和元组文字功能,您可以以更精确的形式表达此意图:`(string DictKey, string DictValue, string MetaData) betterTuple;` 并像这样使用它 `betterTuple.DictKey = "key";` (2认同)

Dan*_*ani 5

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

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)