Cannot figure out why the error…object instance not set to an instance of an object
本问题已经有最佳答案,请猛点这里访问。
对象引用未设置为对象的实例。我仍然有同样的问题…学生的成绩是通过和(学生)的。分数包含一个字符串"80 90 100"
1 2 3 4 5 6 7 8 9 10 11 12 13 | public Student GetUpdatedScores(Student s) { txtName.Text = s.Name; lstScores.Items.Clear(); string[] listOfScores = s.Scores.Split(' '); //receiving error on this line. for (int i = 0; i < (listOfScores.Length - 1); i++) { lstScores.Items.Add(listOfScores[i]); } this.ShowDialog(); return student; } |
显然,
这种问题通过调试会话很容易解决。另外,如果要确保在调试时不知道值不能为空,请使用
1 | Debug.Assert(scoreS != null); |
只是为了让您知道这些调用不会在
作为一个额外的建议,如果你不介意我说,你不应该有只因情况不同而不同的变量。事实上,我认为你应该把
更新:
以下是我将如何写的(有一些评论进一步解释):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // renamed the function to reflect what it really should do (and does) public DialogResult ShowUpdatedScores(Student student) { // since your method is public this is rather good practice if (student == null) throw new ArgumentNullException("student"); // with this, scores cannot be null while you debug without you knowing Debug.Assert(student.Scores != null); // who needs loops when there's AddRange method? :) lstScores.Items.Clear(); lstScores.AddRange(student.Scores.Split(' ')); txtName.Text = student.Name; // it's pointless to return the same student pointer that was passed as a parameter, returning DialogResult makes more sense return this.ShowDialog(); } |
当然,这是对您的代码做了一些假设,但是您得到了这个想法。