【发布时间】:2017-12-27 17:15:00
【问题描述】:
我有一个声明如下的列表:
string[] myList = { "Item One", "Item Two", "Item Three" };
还有一个包含一个元素的字典,其值指向上面的列表:
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("DictionaryItem", myList);
我想通过指向字典中的值来打印myList 的内容。我试过了:
foreach (string element in myDictionary["DictionaryItem"])
{
Console.WriteLine(element);
}
返回语法错误:
foreach 语句不能对 object 类型的变量进行操作,因为 object 不包含 GetEnumerator 的公共定义。
如何通过指向"DictionaryItem" 的值来打印myList?
【问题讨论】:
-
将 myDictionary["DictionaryItem"] 转换为数组或您需要的任何内容。
-
除非有严格的要求,最好尽可能尝试使用强类型对象,例如:
Dictionary<string, string[]>或Dictionary<string, IEnumerable<string>等,在您的情况下,以减少不必要且昂贵的 Casts,您可以获得在受支持的 IDE 中提供智能感知支持。
标签: c# list dictionary foreach