![](/img/trans.png)
[英]Method that takes a list as input parameter where each item is a different generic type
[英]Overloading a method that takes a generic list with different types as a parameter
如何重載采用具有不同類型的泛型列表作為參數的方法?
例如:
我有兩種這樣的方法:
private static List<allocations> GetAllocationList(List<PAllocation> allocations)
{
...
}
private static List<allocations> GetAllocationList(List<NPAllocation> allocations)
{
...
}
有沒有一種方法可以將這兩種方法結合在一起?
當然可以...使用泛型!
private static List<allocations> GetAllocationList<T>(List<T> allocations)
where T : BasePAllocationClass
{
}
這假定您的“分配”,“ PAllocation”和“ NPAllocation”都共享一個稱為“ BasePAllocationClass”的基類。 否則,您可以刪除“ where”約束,並自行檢查類型。
如果您的PAllocation和NPAllocation共享一個公共接口或基類,則可以創建一個只接受這些基對象列表的方法。
但是,如果不這樣做,但是您仍然希望將兩個(或多個)方法組合為一個,則可以使用泛型來實現。 如果方法聲明類似於:
private static List<allocations> GetCustomList<T>(List<T> allocations)
{
...
}
那么您可以使用以下命令調用它:
GetCustomList<NPAllocation>(listOfNPAllocations);
GetCustomList<PAllocation>(listOfPAllocations);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.