在无Main方法的C#类EmployeeClass中调用List.Add报错问题
为什么在C#的EmployeeClass类中调用List.Add会报错?
这其实是C#类结构的基础规则问题,我来给你掰扯清楚:
首先看你写的EmployeeClass代码:
class EmployeeClass { List<string> e = new List<string>(); e.Add("Nitin"); // 这里出错! List<employee> e1 = new List<employee>(); e1.Add(new employee(1,"prakash")); // 这里也出错! }
错误的核心原因
在C#中,类的直接成员区域(也就是类的大括号内部,不属于任何方法、构造函数、属性的部分)只能用来声明成员(字段、方法、属性、嵌套类型等),不能直接写执行语句。
你在EmployeeClass里,声明完List<string> e之后直接写e.Add("Nitin"),这属于「执行逻辑代码」,不属于成员声明,编译器不知道这行代码应该在什么时候执行,自然找不到e.Add的有效上下文,所以会抛出the name 'e.Add' does not exist in the current context的错误。
而你放在Program类的Main方法里的代码是可以正常运行的,因为Main是一个方法的方法体——方法体就是用来写执行逻辑的地方,里面的代码会在方法被调用时按顺序执行,所以List的声明和Add调用都处于有效的执行上下文中,没有问题。
怎么修正EmployeeClass的代码?
你需要把这些执行逻辑放到类的构造函数或者某个方法里,比如:
方法1:放到构造函数里(实例化类时自动执行)
class EmployeeClass { List<string> e = new List<string>(); List<employee> e1 = new List<employee>(); // 构造函数 public EmployeeClass() { e.Add("Nitin"); e1.Add(new employee(1,"prakash")); } }
方法2:放到自定义方法里(需要主动调用才执行)
class EmployeeClass { List<string> e = new List<string>(); List<employee> e1 = new List<employee>(); public void InitializeLists() { e.Add("Nitin"); e1.Add(new employee(1,"prakash")); } } // 使用时: // var empClass = new EmployeeClass(); // empClass.InitializeLists();
这样代码就符合C#的类结构规则,不会再报错啦!
内容的提问来源于stack exchange,提问作者Nitin Prakash
相关产品推荐
相关产品推荐

