将结构放入字典中

时间:2017-12-26 14:57:00

标签: c#

我想在字典中使用结构,其键是字符串,值是结构。我不知道语法是什么,因为我是c#i的新手,之前我正在编写c ++。 顺便说一句,我想从文本文件中读取并将行放在字典中。 这就是我已经做过的事情:

public class CDinfo
{
public string code;
public string type;
public int count;
}
    private void button1_Click(object sender, EventArgs e)
    {
        string pathsource = @"F:\Computer Science\CD & Instruments\CDs.txt";
        CDinfo lolo = new CDinfo();
        string name;
        name = textBox1.Text;
        lolo.type = textBox2.Text;
        lolo.code = textBox3.Text;
        lolo.count = int.Parse(count.Text);
        Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>();
        StreamReader reader = new StreamReader(pathsource);
        while (reader.Peek() != -1)
        {
            string m;
            string[] fasl;
            m = reader.ReadLine();
            fasl = m.Split(',');
            lolo.type = fasl[1];
            lolo.code = fasl[2];
            lolo.count = fasl[3];
            MS.Add(fasl[0], lolo);
        }
        reader.Close();
        StreamWriter sw = new StreamWriter(pathsource, append: true);
        string s = name + ',' + lolo.type + ',' + lolo.code + ',' + lolo.count;
        sw.WriteLine(s);
        sw.Close();
        MessageBox.Show("CD Added Successfully.");
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
 }

运行解决方案后,我收到此错误“索引超出了数组的范围”。

1 个答案:

答案 0 :(得分:0)

每次单击Button1时,您都在初始化一个新字典,并且您没有跟踪它,因此您永远无法在不同的上下文中使用它。您需要将字典定义为类变量,并在click方法中为其添加值:

Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>(); // initialize the dictionary somewhere outside of your click handler

private void button1_Click(object sender, EventArgs e)
{
    CDinfo lolo = new CDinfo();
    string name;
    name = textBox1.Text;
    lolo.type = textBox2.Text;
    lolo.code = textBox3.Text;
    lolo.count = int.Parse(count.Text);

    // add to the dictionary here
    MS.Add(name, lolo);
}

另外,正如一些评论已经提到的那样,CDinfo应该是一个类,而不是结构。