How Can I inherit the string class?

后端 未结 7 2110
春和景丽
春和景丽 2020-12-03 10:03

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:

Er

7条回答
  •  暖寄归人
    2020-12-03 10:40

    System.String is sealed, so, no, you can't do that.

    You can create extension methods. For instance,

    public static class MyStringExtensions
    {
        public static int WordCount(this string inputString) { ... }
    }
    

    use:

    string someString = "Two Words";
    int numberOfWords = someString.WordCount();
    

提交回复
热议问题