Usage of Extension Methods

前端 未结 9 1654
抹茶落季
抹茶落季 2020-12-11 01:51

  • When does using extension methods make sense?
  • Does adding extension methods to a type affect performance?

    These questions are follow up to the question i a

  • 9条回答
    •  囚心锁ツ
      2020-12-11 02:18

      I'm not aware of any performance implications. Using extension methods makes most sense when you don't have access to the source code and thus can't add the method to the class directly, and the method makes sense to be implemented as a function. This goes to the comment I made on your previous question, where one other person gave a sample for an extension method on the 'string' class that returned a bool based on whether the string was a valid email. This, IMO, is an example of when NOT to use an extension method, because that function isn't fundamental to the string type. Adding a Left(int) and a Right(int) function to 'string' does make sense, however.

    提交回复
    热议问题