我有两个类(class)。一个叫人另一个学生。学生继承人。 在我填写表单并将数据传递到下一个表单进行显示之前,一切正常。
除了名称、地址和州以外,一切都显示正常。这些来自 person 类并且具有 NULL 值。让我发疯的是城市、邮政编码和出生日期来自同一类人,而且工作得很好。我不明白为什么会这样,希望有更多知识的人能为我指明正确的方向。
这是两个类:
public class Person
{
private string name;
private string address;
private string city;
private string state;
private string zipcode;
private DateTime birthdate;
public Person()
{
}
public Person(string name, string address, string city, string state, string zipcode, DateTime birthdate)
{
this.name = name;
this.address = address;
this.city = city;
this.state = state;
this.zipcode = zipcode;
this.birthdate = birthdate;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { name = address; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string Zipcode
{
get { return zipcode; }
set { zipcode = value; }
}
public DateTime Birthdate
{
get { return birthdate; }
set { birthdate = value; }
}
}
public class Student : Person
{
private string studentID;
private double gradepointAverage;
private List<string> currentClasses = new List<string>();
public Student()
{
}
public Student(string name, string address, string city, string state, string zipcode, DateTime birthdate, string studentID, double gradepointAverage, List<string> currentClasses)
: base(name, address, city, state, zipcode, birthdate)
{
this.studentID = studentID;
this.gradepointAverage = gradepointAverage;
this.currentClasses = currentClasses;
}
public string StudentID
{
get { return studentID; }
set { studentID = value; }
}
public double GradePointAverage
{
get { return gradepointAverage; }
set { gradepointAverage = value; }
}
public List<string> CurrentClasses
{
get { return currentClasses; }
set { currentClasses = value; }
}
}
这里是我实例化类的地方:
private void btnSave_Click(object sender, EventArgs e)
{
s = new Student();
s.StudentID = txtStudentID.Text;
s.Name = txtName.Text;
s.Address = txtAddress.Text;
s.City = txtCity.Text;
s.State = txtState.Text;
s.Zipcode = txtZipCode.Text;
s.Birthdate = DateTime.Parse(txtBirthdate.Text);
s.GradePointAverage = Convert.ToDouble(txtGradPoint.Text);
string stringItmem;
foreach(Object selectedItem in lstClasses.SelectedItems)
{
stringItmem = selectedItem as String;
s.CurrentClasses.Add(stringItmem);
}
students.Add(s);
resetForm();
MessageBox.Show("Student has been saved.");
}
最佳答案
public string Address
{
get { return address; }
set { name = address; } // Should be "address = value"
}
查看 setter - 你在这里所做的是在不设置 address
的情况下破坏你的 name
。这应该可以解释您所有的数据损坏。由于您在代码中首先设置了 name
,这就解释了为什么它们都是 null
。
关于c# - 继承问题,从继承类的某些数据上获取 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20485061/