如何在C#的Trying类中正确访问其他类的对象值?
问题:跨类访问对象数组元素时触发NullReferenceException
我一直使用C++编程,现在正在学习C#,遇到了访问对象值的问题。以下是我的尝试代码:
class Program { static void Main(string[] args) { StudentInfo[] student = new StudentInfo[2]; student[0] = new StudentInfo(100, 4); student[1] = new StudentInfo(101, 3); Trying ty = new Trying(); ty.trial(); /// 这里出现问题 } } class Trying { StudentInfo[] student = new StudentInfo[2]; // 加这行是为了避免编译错误 public void trial() { Console.WriteLine(student[1].Gpa); // 这里出现问题 } } class StudentInfo { public int studentNo {get; set;} public int Gpa {get; set;} public StudentInfo(int cc, int ct) { studentNo = cc; Gpa = ct; } }
运行时出现错误:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
原因分析
你遇到的问题核心是两个student数组是完全独立的对象:
Main方法里创建的student数组已经初始化了两个StudentInfo实例;Trying类里定义的student数组只是新创建了一个长度为2的空数组,数组里的每个元素都是null,并没有实际的StudentInfo对象,所以访问student[1].Gpa时会触发空引用异常。
C#中类的字段是每个实例独立拥有的,和C++的全局变量/指针共享逻辑不同,同名变量不会自动关联。
解决方法
方法1:通过构造函数传递数组
让Trying类在创建实例时接收外部的数组,保存后再使用:
class Trying { // 用私有字段存储外部传入的数组 private StudentInfo[] _student; // 构造函数接收数组参数 public Trying(StudentInfo[] studentArray) { _student = studentArray; } public void trial() { Console.WriteLine(_student[1].Gpa); } }
修改Main里的调用代码,把初始化好的数组传入:
Trying ty = new Trying(student); ty.trial();
方法2:通过方法参数传递数组
如果不需要在Trying类中长期保存数组,直接在trial方法里接收参数即可:
class Trying { public void trial(StudentInfo[] studentArray) { Console.WriteLine(studentArray[1].Gpa); } }
修改Main里的调用代码:
Trying ty = new Trying(); ty.trial(student);
内容的提问来源于stack exchange,提问作者Euijin Jung
相关产品推荐
相关产品推荐

