• C# 利用范型与扩展方法重构代码


    在一些C#代码中常常可以看到 

    Java代码  收藏代码
    1. //An Simple Example By Ray Linn  
    2. class CarCollection :ICollection  
    3. {  
    4.     IList list;  
    5.       
    6.     public void Add(Car car)  
    7.     {  
    8.          list.Add(car);  
    9.     }  
    10.     .... function list for ICollection...  
    11.       
    12.     public  void listPrice()  
    13.     {  
    14.        foreach(Car car in list)  
    15.            System.Console.WriteLin(car.Price);  
    16.     }  
    17.     ......more specifical function list...  
    18. }  
    19.   
    20. class PetCollection :ICollection  
    21. {  
    22.     IList list;  
    23.   
    24.     public void Add(Pet pet)  
    25.     {  
    26.          list.Add(pet);  
    27.     }  
    28.     .... function list for ICollection...  
    29.       
    30.     public  void FeedPet()  
    31.     {  
    32.        foreach(Pet pet in list)  
    33.            System.Console.WriteLin(pet.Eating());  
    34.     }  
    35.     ......more specifical function list...  
    36. }  



    这样的代码在很多Open Source项目中是很经常看到的,比如Cecil,其共同特点是:某种特定类型的Collection+该Collection特殊的操作,在一个项目中可能充斥着数十个类似的Collection,类似的代码在Java中很难被重构,但是在C#中,却可以借助扩展方法与范型进行代码的精减。 

    首先创建范型的Collection,该例子可以用List<T>来代替,但作为例子,我们假设该List<T>是特殊的(可能有一些delegate) 
    Java代码 
      

    Java代码  收藏代码
    1. public CommonCollection<T>:ICollection<T>     
    2. {     
    3.    IList<T> list     
    4.     
    5.     .... function list for ICollection...     
    6. }    
    7.   
    8. public CommonCollection<T>:ICollection<T>  
    9. {  
    10.    IList<T> list  
    11.   
    12.     .... function list for ICollection...  
    13. }  



    对于Car和Pet的特殊操作,我们通过扩展方法来实现 

    Java代码  收藏代码
    1.     
    2.   
    3. public static class CarExt  
    4. {  
    5.     //Ext Function For CommonCollection<Car> by Ray Linn  
    6.     public static void listPrice(this CommonCollection<Car> collection)  
    7.     {  
    8.        foreach(Car car in collection)  
    9.            System.Console.WriteLin(car.Price);  
    10.     }  
    11.     ......more specifical function list...  
    12. }  
    13.   
    14. public static class PetExt  
    15. {  
    16.       //Ext Function For CommonCollection<Pet> by Ray Linn  
    17.     public static void FeedPet(this CommonCollection<Pet> collection)  
    18.     {  
    19.        foreach(Pet pet in list)  
    20.            System.Console.WriteLin(pet.Eating());  
    21.     }  
    22. }  



    通过这样的方式,我们就实现了重构,两个Collection实现了求同存异。在我重构的Cecil之后,编译后的Assemly大小减小了一半.

  • 相关阅读:
    UVa 1592 Database(巧用map)
    TZOJ 4746 Xiangqi(模拟棋盘数组)
    TZOJ 1545 Hurdles of 110m(01背包dp)
    TZOJ 2754 Watering Hole(最小生成树Kruskal)
    TZOJ 1242 求出前m大的数(预处理)
    TZOJ 5280 搜索引擎(模拟字符串)
    TZOJ 4865 统计单词数(模拟字符串)
    TZOJ 5279 马拉松比赛(广搜)
    [luogu4735]最大异或和
    小奇回地球
  • 原文地址:https://www.cnblogs.com/gc2013/p/3831102.html
Copyright © 2020-2023  润新知