C#类对象字段赋值异常输出全0,如何正确初始化对象?
C#对象字段赋值异常问题
本人一直使用C++开发,现转型学习C#。尝试创建多个对象并访问其数据,但结果不符合预期。
编写的代码:
class Students { static void Main(string[] args) { StudentInfo[] student = new StudentInfo[2]; student[0] = new StudentInfo(100, 4); student[1] = new StudentInfo(101, 3); for (int i = 0; i < 2; i++) { Console.WriteLine(student[i].studentNo); Console.WriteLine(student[i].GPA); } } class StudentInfo { public int studentNo, GPA; public StudentInfo(int cc, int ct) { int studentNo = cc; int GPA = ct; } } }
预期输出:
100 4 101 3
实际输出:
0 0 0 0
同时收到警告:warning CS0649: Field 'Students.StudentInfo.GPA' is never assigned to, and will always have.
问题原因
你在StudentInfo的构造函数里,重新声明了局部变量studentNo和GPA,这两个局部变量会覆盖类的同名字段,导致类的字段根本没被赋值,所以默认初始化为0(值类型的默认值)。
解决方法
去掉构造函数里变量前的int声明,直接给类的字段赋值:
class StudentInfo { public int studentNo, GPA; public StudentInfo(int cc, int ct) { studentNo = cc; GPA = ct; } }
或者更规范一点,用this关键字明确指定是类的字段(尤其当参数名和字段名相同时推荐这么做):
class StudentInfo { public int studentNo, GPA; public StudentInfo(int studentNo, int gpa) { this.studentNo = studentNo; this.GPA = gpa; } }
修改后再运行,就能得到你预期的输出了。
内容的提问来源于stack exchange,提问作者Euijin Jung
相关产品推荐
相关产品推荐

