重载采用具有不同类型的通用列表作为参数的方法 [英] Overloading a method that takes a generic list with different types as a parameter
本文介绍了重载采用具有不同类型的通用列表作为参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何重载采用具有不同类型的泛型列表作为参数的方法?
How can I overload 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)
{
...
}
有没有办法将这两种方法结合在一起?
Is there a way I can combine these 2 methods into one?
推荐答案
当然可以...使用泛型!
Sure can... using generics!
private static List<allocations> GetAllocationList<T>(List<T> allocations)
where T : BasePAllocationClass
{
}
这假设您的分配","PAllocation"和"NPAllocation"都共享一些称为"BasePAllocationClass"的基类.否则,您可以删除"where"约束,并自行检查类型.
This assumes that your "allocations", "PAllocation" and "NPAllocation" all share some base class called "BasePAllocationClass". Otherwise you can remove the "where" constraint and do the type checking yourself.
这篇关于重载采用具有不同类型的通用列表作为参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文