比如说建立了一个类Student包含字段name,age,hobby
用name作为Keys
Dictionary<string, Student> stu = new Dictionary<string, Student>();
stu.Add(s1.Name,s1);
stu.Add(s2.Name,s2);
stu.Add(s3.Name,s3);
添加好了数据 遍历Value可以写
foreach (Student ss in stu.Values)
{
Student ass = (Student)ssss;
MessageBox.Show(ass.Name.ToString());
}
那么遍历Keys都时候具体怎么写?
foreach (Student ss in stu.Keys)
{
}
参考答案:foreach (Student ss in stu.Values)
{
//Student ass = (Student)ssss;//这句话没用还是错误的
MessageBox.Show(ss.Name.ToString()); //ass改成ss
}
那么遍历Keys都时候具体怎么写?
//foreach (Student ss in stu.Keys)//这句话是错误的KEYS是string
foreach (string key in stu.Keys) //这样遍历
{
MessageBox.Show(key);
}
}