我試圖編寫一個方法,返回一個字典,但它似乎最終是空的。 你能找出我做錯了什麼嗎?C#返回字典
當我點擊按鈕來搜索一個鍵,它給出了錯誤:詞典中沒有鍵。
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);
}
什麼是myDic?它初始化的地方? – wudzik
不應該是'var myDic = Person.Metod();'? – Andrei