How to extend C# built-in types, like String?

前端 未结 5 1826
别那么骄傲
别那么骄傲 2020-11-28 23:13

Greetings everyone... I need to Trim a String. But I want to remove all the repeated blank spaces within the String itself, not only at the end or

5条回答
  •  心在旅途
    2020-11-28 23:28

    There's a yes and a no to your question.

    Yes, you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type.

    public static string ConvertWhitespacesToSingleSpaces(this string value) {...}
    
    // some time later...
    "hello world".ConvertWhitespacesToSingleSpaces()
    

    No, you cannot call this method Trim(). Extension methods do not participate in overloading. I think a compiler should even give you a error message detailing this.

    Extension methods are only visible if the namespace containing the type that defines the method is using'ed.

提交回复
热议问题