我正在尝试编写一个简单的员工注册表,我想使用一个通用列表来“保存”我正在创建的人员。
管理器类有一个构造函数和一个方法(见下文)。 构造函数创建 List 并且方法添加到它,或者应该添加到它。 问题是我不能像下面那样做,因为 Visual Studio 说 employeeList 在当前上下文中不存在。我还打算怎么写这个?
public EmployeeManager()
{
List<string> employeeList = new List<string>();
}
public void AddEmployee()
{
employeeList.add("Donald");
}
最佳答案
你需要让employeeList成为类的成员变量:
class EmployeeManager
{
// Declare this at the class level
List<string> employeeList;
public EmployeeManager()
{
// Assign, but do not redeclare in the constructor
employeeList = new List<string>();
}
public void AddEmployee()
{
// This now exists in this scope, since it's part of the class
employeeList.add("Donald");
}
}
关于c# - 如何添加到尚未创建的列表。请帮忙!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375221/