Usage of Extension Methods

前端 未结 9 1656
抹茶落季
抹茶落季 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:19

      When does using extension methods make sense?

      They make sense when you are using LINQ and want to chain or pipe functional output from one function to another. It improves the readability of the code and allows you to express a concept more elegantly (whatever that is worth).

      They also allow you to give the appearance of instance methods on any type you like without modifying the source of that type, this can often help readability and the expressiveness of your code when it is used reasonably

      Does adding extension methods to a type affect performance?

      Note that an extension method call like:

      instance.SomeExtensionMethod()
      

      gets compiled to:

      StaticExtensionMethodClass.SomeExtensionMethod(instance);
      

      so performance will be the same as any other static method call.

      0 讨论(0)
    • 2020-12-11 02:23

      From my answer here:

      As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.

      Take a look at the following example:

      public class extended {
          public int sum() {
              return 7+3+2;
          }
      }
      
      public static class extending {
          public static float average(this extended extnd) {
              return extnd.sum() / 3;
          }
      }
      

      As you see, the class Extending is adding a method named average to class Extended. To get the average, you call average method, as it belongs to extended class:

      extended ex = new extended();
      
      Console.WriteLine(ex.average());
      

      Reference: http://aspguy.wordpress.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/


      As regards Performance, I think you can see an improvement with Extension methods since they are never dispatched dynamically, but it all depends on how the dynamic method is implemented.

      0 讨论(0)
    • 2020-12-11 02:24

      Another interesting use of extension methods is when you would like to have certain functionality added to a class under one namespace but not another. One specific example is adding methods to ease unit testing - you wouldn't want them cluttering your production assemblies, but they're great to have when writing unit tests.

      0 讨论(0)
    提交回复
    热议问题