我有一个包含字符串和字典属性的类:
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 -
对象引用未设置为对象的实例。
我在这里缺少什么?
答案 0 :(得分:1)
您应该在Student对象的每个实例中创建一个LevelGpa实例:
List<Student> students = new List<Student>()
{
{new Student() {
StudentId = 1,
LevelGpa = new Dictionary<string, decimal>() {"Freshmen",3.1m}
}
},
...
};