我有以下代码使用使用状态和大写字母的类和字典,但是我无法通过循环来检索值。需要帮助来清除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>
需要帮助来了解如何正确检索值。
答案 0 :(得分:1)
您的GetStates()
方法返回Dictionary<string, State>
,因此在这一行
var theState= State.GetStates();
变量theState
被分配为类型Dictionary<string, State>
。但是在下面的 foreach 块中,您尝试以KeyValuePair<string, object>
的形式访问字典的值。
所以您必须像这样使用它:
foreach (KeyValuePair<string, State> entry in theState)
{
Console.WriteLine(entry.Key + " State Capital is " + entry.Value.Capital);
}
答案 1 :(得分:0)
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);
}
答案 2 :(得分:0)
将代码段更改为下面的代码即可解决您的问题
foreach (KeyValuePair<string, State> entry in theState)
{
Console.WriteLine(entry.Key + " State Capital is " + entry.Value.Capital);
}
但是要了解为什么会收到该错误,您可能需要仔细研究Dictionary<TKey, TValue>
的定义,该定义源自IEnumerable<KeyValuePair<TKey, TValue>>
。因此,当您使用foreach循环时,它在内部作用于IEnumerable<KeyValuePair<TKey, TValue>>
。在此,编译器期望foreach中的每个实体均为KeyValuePair<TKey, TValue>
类型。现在,由于在字典中您拥有TValue
属于State类型,因此编译器期望KeyValuePair<string, State>
的原因。现在,要对此有更深入的了解,您可能需要阅读“协变和反变概念c#”