我有一个类计数器,可以通过键值对进行计数。简化版如下:
public class Counter<T> {
private Dictionary<T, int> counts;
public void Increment(T key) {
int current;
bool exists = counts.TryGetValue(key, out current);
if (exists) {
counts[key]++;
} else {
counts[key] = 1;
}
}
}
它还有其他一些根据我的需求进行特殊处理的功能,但这就是本质。到目前为止,它运行得很好。
现在我想让它可以在Linq查询中使用(包括键和值)。为了实现这个目标,我认为需要实现:
IEnumerable<T, int>
所以我添加了:
public class Counter<T> : IEnumerable<KeyValuePair<T, int>> {
// ...
IEnumerator<KeyValuePair<T, int>>
IEnumerable<KeyValuePair<T, int>>.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<T, int>>)counts).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return counts.GetEnumerator();
}
很不幸的是,这会导致编译器错误
提供的泛型参数数量与泛型类型定义的元数不相等。参数名称:实例化
问题
- 什么是元数?
- 我是否正在正确地使此类型可从Linq使用?
- 如何修复实现?
更新:笔误
我在简化代码以发布时发生了笔误。事实上,该代码正试图实现 IEnumerable<KeyValuePair<T, int>>
而不是 IEnumerable<T, int>
IEnumerable<KeyValuePair<T, int>>
。 - Eric J.