繁体   English   中英

重载采用具有不同类型的通用列表作为参数的方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM