How Can I inherit the string class?

后端 未结 7 2132
春和景丽
春和景丽 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:58

    You can't inherit a sealed class (that's the whole point of it) and the reason why it wouldn't work with both string and System.String is that the keyword string is simply an alias for System.String.

    If you don't need to access the internals of the string class, what you can do is create an Extension Method, in your case :

    //note that extension methods can only be declared in a static class
    static public class StringExtension {
    
        static public  int WordCount(this string other){
            //count the word here
            return YOUR_WORD_COUNT;
        }
    
    }
    

    You still won't have access to the private methods and properties of the string class but IMO it's better than writing :

    StringHelper.WordCount(yourString);
    

    That's also how LINQ works.

提交回复
热议问题