填充字典会抛出NullReferenceEexception

时间:2017-03-29 21:48:01

标签: c#

我有一个包含字符串和字典属性的类:

public class Student
{
    public int StudentId { get; set; }
    public Dictionary<string, decimal> LevelGpa { get; set; }
}

我想填写一份学生名单:

List<Student> students = new List<Student>()
{
    {new Student{StudentId = 1, LevelGpa = {{"Freshmen",3.1m}}}},
    {new Student{StudentId = 1, LevelGpa = {{"Sophomore",3.2m}}}},
    ...
};

但它在运行时抛出NullReferenceException -

  

对象引用未设置为对象的实例。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您应该在Student对象的每个实例中创建一个LevelGpa实例:

List<Student> students = new List<Student>()
{
    {new Student() {
                    StudentId = 1, 
                    LevelGpa = new Dictionary<string, decimal>() {"Freshmen",3.1m} 
                   }
    },

    ...
};