我真的是c#的初学者,遇到了这个问题,即使花了几个小时在网上搜索也无法解决。我不明白为什么堆栈对象Grades总是为null,每次运行应用程序时,都会抛出“System.NullReferenceException”的异常。当我将鼠标悬停在Grades上的鼠标上时,它表示“字段'Student.Grades'永远不会分配给它,并且总是将其默认值设为null”。我也不能使用“{get; set;}”来访问这个属性。所以有人能告诉我为什么吗?非常感谢!!!(第一次询问堆栈溢出的问题,抱歉格式错误)
class Student : Person
{
public int studentID { get; set; }
public static int nextID;
public Stack<int> Grades;
public Student(string firstName, string lastName, DateTime birthDate,
string address1, string address2, string city, string state,
string zip, string country)
{
FirstName = firstName;
LastName = lastName;
BirthDate = birthDate;
Address1 = address1;
Address2 = address2;
City = city;
State = state;
Zip = zip;
Country = country;
//track the number of students enrolled
studentID = nextID;
nextID++;
}
}
答案 0 :(得分:0)
在构造函数中,您可以添加
this.Grades = new Stack();
码
c#中的类具有null默认值。