我试图编写一个返回Dictionary的方法,但似乎它最终是空的。 你能找出我做错了吗?
当我单击按钮搜索某个键时,它会显示错误:词典不包含任何键。
class Person
{
public int PersNr { get; set; }
public string Name { get; set; }
public string BioPappa { get; set; }
public Adress Adress { get; set; }
public static Dictionary<int, Person> Metod()
{
var dict = new Dictionary<int, Person>();
dict.Add(870603, new Person
{
Name = "Jonathan",
PersNr = 870603,
BioPappa = "Jarmo",
Adress = new Adress
{
Land = "Sverige",
PostNr = 73249,
Stad = "Arboga"
}
});
dict.Add(840615, new Person
{
Name = "Lina",
PersNr = 840615,
BioPappa = "Erik"
});
return dict;
}
namespace WindowsFormsApplication148
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Person.Metod();
var person = myDic[int.Parse(textBoxSok.Text)];
listBox1.Items.Add(person.Name);
listBox1.Items.Add(person.PersNr);
listBox1.Items.Add(person.BioPappa);
listBox1.Items.Add(person.Adress.Stad);
listBox1.Items.Add(person.Adress.PostNr);
listBox1.Items.Add(person.Adress.Land);
}
答案 0 :(得分:2)
当你打电话给你的方法时(请使用更有意义且更少混淆的名字)你需要收到它的工作结果
private void button1_Click(object sender, EventArgs e)
{
Dictionary<int, Person> myDic = person.Metod();
var person = myDic[int.Parse(textBoxSok.Text)];
.......
但是,您没有显示所有代码,因为如您的问题所示,代码无法编译。我想你已经在某处声明了AND INITIALIZED变量myDic
,因为你需要在表单的不同部分使用它。这有点需要更好地分析,因为对Metod
的调用将局部变量myDic
重新初始化为方法调用返回的Dictionary。
答案 1 :(得分:2)
private void button1_Click(object sender, EventArgs e)
{
//WRONG
Person.Metod();
您执行方法但不将结果分配给任何内容。