多类实例化关联问题:添加Student时提示schoolRoster不存在
问题修复方案
核心问题分析
你遇到的schoolRoster不存在于当前上下文错误,根源是:schoolRoster是school类的私有字段,而Operation类的静态方法没有任何渠道访问到这个字段。除此之外,代码里还有几个小问题需要一并修正:
具体修复步骤
调整类的职责(更合理的设计)
把操作学生名册的方法直接放到school类里——这些操作本来就是针对学校的名册,这样就不用跨类访问私有字段了。如果一定要保留Operation类,那就得让它接收school实例作为参数,不过前者的设计更符合面向对象的原则。修正student类的字段访问权限
要么把Name和Form改成public,要么给它们添加公共的只读属性,不然外部类没法读取这些值。修正变量名和引用错误
PrintForm方法里的Student是大写,和类名student不一致,要统一成小写。- foreach循环里判断的是
stu.Form,不是未定义的st.Form。
修复后的完整代码
using System; using System.Collections.Generic; class Exercises { public static void Main(string[] args) { school Showers = new school(); student Lenny = new student("Lenny", 4); Showers.AddStudent(Lenny); // 测试打印所有学生 Showers.PrintAll(); // 测试打印指定年级的学生 Showers.PrintForm(4); } } public class student { public string Name { get; private set; } public int Form { get; private set; } public student(string n, int f) { Form = f; Name = n; } } public class school { private List<student> schoolRoster = new List<student>(); public void AddStudent(student st) { schoolRoster.Add(st); } public void PrintForm(int num) { foreach (student stu in schoolRoster) { if (stu.Form == num) { Console.WriteLine(stu.Name); } } } public void PrintAll() { foreach (student stu in schoolRoster) { Console.WriteLine($"{stu.Name} in form {stu.Form}"); } } }
说明
- 把
AddStudent、PrintForm、PrintAll移到school类后,直接操作自身的schoolRoster字段,彻底解决了跨类访问私有成员的问题。 - 给
student类的字段用了只读自动属性,既保证外部能读取值,又不会被随意修改。 - Main方法里直接调用实例化的
school对象的方法,逻辑更清晰直观。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

