Overloading a method that takes a generic list with different types as a parameter

梦想的初衷 提交于 2020-01-16 20:55:42

问题


How can I overload a method that takes a Generic List with different types as a parameter?

For example:

I have a two methods like so:

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?


回答1:


Sure can... using generics!

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

}

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.




回答2:


If your PAllocation and NPAllocation share a common interface or base class, then you can create a method that just accepts a list of those base objects.

However, if they do not, but you still wish to combine the two(or more) methods into one you can use generics to do it. If the method declaration was something like:

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

then you can call it using:

GetCustomList<NPAllocation>(listOfNPAllocations);
GetCustomList<PAllocation>(listOfPAllocations);


来源:https://stackoverflow.com/questions/926801/overloading-a-method-that-takes-a-generic-list-with-different-types-as-a-paramet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!