Partial Class vs Extension Method

前端 未结 9 1671
無奈伤痛
無奈伤痛 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:10

    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 data. I want to extend each class somehow to give me the option of receiving the data in the format IEnumerable.

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

    public static class ExtensionMethods
    {
        public static IEnumerable ToMediaItems(this IEnumerable 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..
    

提交回复
热议问题