C#通用通配符

时间:2014-11-10 17:48:10

标签: java c# generics collections bounded-wildcard

我花了很多时间解决这个问题,但我无法弄明白。 我有以下Java方法签名:

public static <T> boolean isSameCollectionSets(
    Collection<? extends Collection<T>> set1, 
    Collection<? extends Collection<T>> set2)

此方法采用类型为T的两个集合集合。它在Java中工作。此外,编译器在传递正确的参数时能够自己获取类型T.

现在我想将这个完全相同的方法移植到C#。到目前为止,我有这个:

public static bool IsSameCollectionSets<T>(ICollection<T> set1, ICollection<T> set2) 
    where T : ICollection<T>

但是,当我尝试在C#中执行以下操作时,这会失败:

ICollection<List<int>> collection1 = new List<List<int>>();
ICollection<HashSet<int>> collection2 = new HashSet<HashSet<int>>();

var result = IsSameCollectionSets(collection1, collection2);

IsSameCollectionSets 方法带有下划线,编译器说:

“无法从用法中推断出方法'bool IsSameCollectionSets(ICollection,ICollection)'的类型参数。请尝试明确指定类型参数。”

现在,我试图明确地给出类型参数,但到目前为止还没有任何工作。

我的错误在哪里? 非常感谢提前!

1 个答案:

答案 0 :(得分:0)

感谢@Rob,我找到了一个有效的解决方案。

我没有使用ICollection<T>,而是使用IEnumerable<T>

public static bool IsSameCollectionSets<T>(IEnumerable<IEnumerable<T>> set1,
IEnumerable<IEnumerable<T>> set2)

此外,与问题中的代码相比,我使用接口进行实例化:

ICollection<IList<int>> collection1 = new List<IList<int>>();
ICollection<ISet<int>> collection2 = new HashSet<ISet<int>>();