【发布时间】:2019-03-02 14:50:46
【问题描述】:
我有以下代码,使用了接受状态和资本的类和字典,但我无法通过循环检索这些值。需要帮助是清除foreach 循环中发生的错误。
public class State {
public string Capital { get; set; }
public int Population { get; set; }
public int Size { get; set; }
public State(string aCapital, int aPopulation, int aSize) {
Capital = aCapital;
Population = aPopulation;
Size = aSize;
} // Constructor of the class State
public static Dictionary<string, State> GetStates() {
Dictionary<string, State> myStates = new Dictionary<string, State>(); // need the () because its a class
// myStates takes 2 values, one is a string , that is a state and State , which is inturn takes 3 values -
// Capital,Population, size
State addStateCapital = new State("Montgomery", 214141, 244);
myStates.Add("Alabama", addStateCapital);
// second set
addStateCapital = new State("Sacramento", 214141, 244);
myStates.Add("California", addStateCapital);
return myStates;
}
}
我的主程序如下..但我得到错误..
var theState= State.GetStates();
// this prints one item in a dictionary
Console.WriteLine("State Capital of California is " + theState["California"].Capital);
foreach (KeyValuePair<string,object> entry in theState)
{
Console.WriteLine(entry.Key + " State Capital is " + entry.Value.ToString());
}
foreach 上的错误:
Cannot convert keyvaluePair <string,DictionaryDemo.State> to System... Generic KVP<string,object>
在了解如何正确检索值方面需要帮助。
【问题讨论】:
-
它在错误信息中告诉你错误;您正在尝试将
KeyValuePair<string, State>转换为KeyValuePair<string, object>。我建议只使用foreach (var entry in theState)。
标签: c# .net dictionary