`

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

阅读更多
在一些C#代码中常常可以看到
//An Simple Example By Ray Linn
class CarCollection :ICollection
{
    IList list;
    
    public void Add(Car car)
    {
         list.Add(car);
    }
    .... function list for ICollection...
    
    public  void listPrice()
    {
       foreach(Car car in list)
           System.Console.WriteLin(car.Price);
    }
    ......more specifical function list...
}

class PetCollection :ICollection
{
    IList list;

    public void Add(Pet pet)
    {
         list.Add(pet);
    }
    .... function list for ICollection...
    
    public  void FeedPet()
    {
       foreach(Pet pet in list)
           System.Console.WriteLin(pet.Eating());
    }
    ......more specifical function list...
}


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

首先创建范型的Collection,该例子可以用List<T>来代替,但作为例子,我们假设该List<T>是特殊的(可能有一些delegate)
Java代码
 
public CommonCollection<T>:ICollection<T>   
{   
   IList<T> list   
  
    .... function list for ICollection...   
}  

public CommonCollection<T>:ICollection<T>
{
   IList<T> list

    .... function list for ICollection...
}



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

public static class CarExt
{
    //Ext Function For CommonCollection<Car> by Ray Linn
    public static void listPrice(this CommonCollection<Car> collection)
    {
       foreach(Car car in collection)
           System.Console.WriteLin(car.Price);
    }
    ......more specifical function list...
}

public static class PetExt
{
      //Ext Function For CommonCollection<Pet> by Ray Linn
    public static void FeedPet(this CommonCollection<Pet> collection)
    {
       foreach(Pet pet in list)
           System.Console.WriteLin(pet.Eating());
    }
}


通过这样的方式,我们就实现了重构,两个Collection实现了求同存异。在我重构的Cecil之后,编译后的Assemly大小减小了一半.
分享到:
评论
3 楼 hd700 2008-06-14  
扩展方法对泛型的操作可以看作是一种特化,不过当面对大量的Car,Pet类时这样做要累死人的
2 楼 singleblue 2008-05-10  
不错,学习一下
1 楼 ray_linn 2008-04-03  
重构之后,Collection的操作速度大概有1~3倍的提高,这是由于C#的范型实现方式优于Java的擦除法,从而消除了拆箱和装箱的损耗。

相关推荐

Global site tag (gtag.js) - Google Analytics