我有以下使用类和字典的代码,该类和字典需要状态和资本,但我无法通过循环来检索值。需要帮助来清除 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>
需要帮助了解如何正确检索值。
最佳答案
1) 在KeyValuePair<,>中使用State而不是Object。 由于您已经在 State.GetStates() 返回类型中指定了
Dictionary<string, State>
2) 同时将entry.Value.ToString()更改为entry.Value.Capital。因为它不会显示状态名称,而是显示类对象名称。因此,更改它 entry.Value.Capital
foreach (KeyValuePair<string,State> entry in theState)
{
Console.WriteLine(entry.Key + " State Capital is " + entry.Value.Capital);
}
关于c# - 在 C# 中循环字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959767/