我想创建一个遍历键值集合的方法。我希望确保我的方法支持任何扩展KeyedCollection<string, Collection<string>>的集合的迭代
下面是方法:
public void IterateCollection(KeyedCollection<string, Collection<string>> items)
{
foreach (??? item in items)
{
Console.WriteLine("Key: " + item.Key);
Console.WriteLine("Value: " + item.Value);
}
}它显然不起作用,因为我不知道应该用哪种类型来替换循环中的问号。我不能简单地放入object或var,因为稍后我需要在循环体中调用Key和Value属性。我要找的是什么类型的?谢谢。
发布于 2011-11-11 22:14:30
KeyedCollection<TKey, TItem>实现了ICollection<TItem>,因此在本例中您将使用:
foreach(Collection<string> item in items)这也是var会给你的。在KeyedCollection中,您不会获得键/值对-您只会获得值。
有没有可能KeyedCollection真的不是最适合你使用的类型?
发布于 2011-11-11 22:16:43
根据KeyedCollection枚举器的定义,项目类型将是Collection<String>。您不能随意决定使用适当的类型,以便在迭代不支持的情况下同时获得Key和Value,在本例中不支持。请注意,使用显式类型和var是完全相同的。
如果您希望在迭代中同时使用Key和Value,则需要使用Dictionary<string, Collection<string>>类型。
https://stackoverflow.com/questions/8095154
复制相似问题