2009-05-29 40 views
0

如何重载以不同类型的通用列表作为参数的方法?重载以不同类型的通用列表作为参数的方法

例如:

我有两个方法,像这样:

private static List<allocations> GetAllocationList(List<PAllocation> allocations) 
{ 
    ... 
} 

private static List<allocations> GetAllocationList(List<NPAllocation> allocations) 
{ 
    ... 
} 

有没有一种方法可以让我这2种方法结合成一个?

回答

4

当然可以...使用泛型!

private static List<allocations> GetAllocationList<T>(List<T> allocations) 
    where T : BasePAllocationClass 
{ 

} 

这是假设你的“分配”,“PAllocation”和“NPAllocation”称为“BasePAllocationClass”都有着一些基类。否则,您可以删除“where”约束并进行类型检查。

+0

我使用你的建议,但我怎么去这样做的类型检查? 我也需要遍历allocations参数。我尝试使用allocations.ForEach(委托(PAllocation pa){...});但我得到一个错误,说不兼容的匿名函数签名。有任何想法吗? – Jon 2009-05-29 16:35:23

+0

你不能只是做(分配的foreach var)? – womp 2009-05-29 16:43:39

1

如果您的PAllocation和NPAllocation共享通用接口或基类,那么您可以创建一个方法来接受这些基础对象的列表。但是,如果他们不这样做,但您仍然希望将两种(或多种)方法合并为一种,则可以使用泛型来执行此操作。如果方法声明是这样的:

private static List<allocations> GetCustomList<T>(List<T> allocations) 
{ 
    ... 
} 

,那么你可以调用它使用:

GetCustomList<NPAllocation>(listOfNPAllocations); 
GetCustomList<PAllocation>(listOfPAllocations); 
相关问题