2009-05-29 33 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); 
相關問題