【问题标题】:Overloading a method that takes a generic list with different types as a parameter重载将不同类型的泛型列表作为参数的方法
【发布时间】:2009-05-29 16:05:15
【问题描述】:

如何重载将不同类型的通用列表作为参数的方法?

例如:

我有两种方法:

private static List<allocations> GetAllocationList(List<PAllocation> allocations)
{
    ...
}

private static List<allocations> GetAllocationList(List<NPAllocation> allocations)
{
    ...
}

有没有办法可以将这两种方法合二为一?

【问题讨论】:

    标签: c# .net generics overloading


    【解决方案1】:

    当然可以...使用泛型!

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

    这假设您的“allocations”、“PAllocation”和“NPAllocation”都共享一些名为“BasePAllocationClass”的基类。否则,您可以删除“where”约束并自己进行类型检查。

    【讨论】:

    • 我正在使用您的建议,但我该如何进行类型检查?我还需要迭代分配参数。我尝试使用 allocations.ForEach(delegate(PAllocation pa){...});但我收到一个错误,显示不兼容的匿名函数签名。有什么想法吗?
    • 你不能只做(foreach var in allocations)吗?
    【解决方案2】:

    如果您的 PAllocation 和 NPAllocation 共享一个公共接口或基类,那么您可以创建一个只接受这些基对象列表的方法。

    但是,如果他们不这样做,但您仍希望将两个(或多个)方法组合为一个,则可以使用泛型来实现。如果方法声明类似于:

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

    然后你可以使用:

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

    【讨论】:

    • 和 部分可以省略,因为类型会自动推断
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多