开发者

Partial Class vs Extension Method

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 people using a partial class to extend an entity class in a project. Meanwhile, in the same project, there is another folder containing a lot extension methods to the entit开发者_如何学Cy class.

Is it right to do so? I mean these 2 ways both work well. Could you give me some real idea of how to pick one or the other when I want extend a class?


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


Partial classes should be used in code generation scenarios.

Since the generated file might get overwritten at any time, one uses partial classes to write into the non-generated file.

Additionally, partials will only work if they are part of the same assembly - they cannot cross assembly boundaries.

If these are not your constraints, you can and should use extension methods - of course, after considering other possibilities such as inheritance and composition for suitability.


You can use extension methods on a NULL instance but not instance methods (of partial classes or otherwise). This is a consequence of extension methods actually being static.


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()).


you can use partial classes in a project you're developing, while extension methods could be used also to extend projects you don't have source code too..


Partial works only if both files are in the same project, and you can access private and protected members of that class.

Extension methods are just static methods, and can't access private members.

So if you want to access private and protected members, only way you have is partial, if no, answer to the question, should the method you want to add be visible everywhere you want to use class? if yes, use partial, if no, it's some kind of extension, use extension methods.

By the way, if the first class is not generated by some tool, you can write your function there except of using partial ;)

hope this helps


If you choose the Partial Class route but find you are repeating the same code, switch to Extension Methods.

For example, i have many generated classes with methods which return IEnumerable<Track> data. I want to extend each class somehow to give me the option of receiving the data in the format IEnumerable<MediaItem>.

I have a general requirement here to transform IEnumerable<Track> data to IEnumerable<MediaItem>. In this case, rather than writing multiple partial class methods an extension method works best:

public static class ExtensionMethods
{
    public static IEnumerable<MediaItem> ToMediaItems(this IEnumerable<Track> tracks)
    {
        return from t in tracks
               select new MediaItem
               {
                   artist = t.Artist,
                   title = t.Title,
                   // blah blah
               };
    }
}

This gives me the following options:

var data = Playlist.Tracks.ToMediaItems();
var data = Podcast.Tracks.ToMediaItems();
// etc..


A partial class is useful when you want to extend a generated class. This way you can write your code in one file, and then when/if the other 'part' of your class needs to be re-generated, it can be done safely, as that code file hasn't changed.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜