Partial Class vs Extension Method

前端 未结 9 1668
無奈伤痛
無奈伤痛 2021-02-01 02:09

I dont have much experience of using these 2 ways to extend a class or create extension methods against a class. By looking others work, I have a question here.

I saw pe

相关标签:
9条回答
  • 2021-02-01 02:25

    Some of differences that will determine whether you want to use a Partial Class or an Extension Method are

    Partial Class

    • Only works against classes in the same project/assembly
    • Target class has to be marked as partial
    • Has access to the Target class' fields and protected members
    • Target must be a class implementation

    Extension Method

    • Can be applied against classes in other assembles
    • Must be static, has access to only the Target classes public members
    • Target of extension can be a concrete type, or an abstract type or interface
    0 讨论(0)
  • 2021-02-01 02:31
    Partial Class - 
    

    split the definition of a class or a struct, or an interface over two or more source files

    Extension Method  
    

    Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type

    0 讨论(0)
  • 2021-02-01 02:36

    I use partial methods when I need a class to implement an interface, but the class code is autogenerated (VS uses partial classes to generate code for both web services and EF models).

    I use extension methods when the new method that I'm adding to the type is appropriate for any value of that type. (good examples: int.IsEven(), string.IsEmpty(); bad examples: int.IsOldEnoughToDrive(), string.IsLastName()).

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