如何继承字符串类? [英] How Can I inherit the string class?
本文介绍了如何继承字符串类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想继承以扩展 C# 字符串类以添加诸如 WordCount()
和其他许多方法,但我一直收到此错误:
I want to inherit to extend the C# string class to add methods like WordCount()
and several many others but I keep getting this error:
错误 1 'WindowsFormsApplication2.myString':无法从密封派生输入字符串"
Error 1 'WindowsFormsApplication2.myString': cannot derive from sealed type 'string'
有没有其他方法可以解决这个问题?我尝试使用 string
和 String
但它没有用.
Is there any other way I can get past this ? I tried with string
and String
but it didn't work.
推荐答案
System.String 是密封的,所以,不,你不能这样做.
System.String is sealed, so, no, you can't do that.
您可以创建扩展方法.例如,
public static class MyStringExtensions
{
public static int WordCount(this string inputString) { ... }
}
使用:
string someString = "Two Words";
int numberOfWords = someString.WordCount();
这篇关于如何继承字符串类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文