从文本文件创建和存储 class 个对象的值

Creating and storing values of class objects from a text file

我正在尝试找到一种方法来从文件中创建 class 实例,并将该文件用作为 class 属性提供值的方法。我可以手动将所有信息放入,但最好通过文件来完成,这样我可以更改文件,这将为我更改程序。

这是到目前为止的代码...当我 运行 它时,它说

class Program
{
    class dish
{
     public class starters { public string starter; public string alteration; }


    static void Main(string[] args)
    {
        List<dish.starters> starter = new List<dish.starters>();
        using (StreamReader reader = File.OpenText(@"D:\Visual Studio\Projects\Bella Italia\Food\Starters.txt"))
        {
            IDictionary<string, dish.starters> value = new Dictionary<string, dish.starters>();
            while (!reader.EndOfStream)
            {
                value[reader.ReadLine()] = new dish.starters();
                value[reader.ReadLine()].starter = reader.ReadLine();
            }
            foreach(var x in value.Values)
            {
                Console.WriteLine(x.starter);
            }

        }

        Console.ReadLine();

    }
}

}

当我尝试 运行 时,它显示

异常未处理 System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'

您正在阅读这里连续两行。第二行可能在字典中没有相关条目(您也不希望重复):

value[reader.ReadLine() /*one*/] = new dish.starters();
value[reader.ReadLine() /*two*/].starter = reader.ReadLine();

将密钥存储在变量中并重复使用:

string key = reader.ReadLine();

value[key] = new dish.starters();
value[key].starter = reader.ReadLine();

或创建对象并稍后赋值:

string key = reader.ReadLine();

var starters = new dish.starters();
starters.starter = reader.ReadLine()

value[key] = starters;