如何添加到尚未创建的列表.请帮忙!

Mar*_*enn 2 c# list

我正在尝试编写一个简单的员工注册表,我想使用通用List来"保存"我正在创建的人员.

manager类有一个构造函数和一个方法(见下文).构造函数创建List并且方法添加到它,或者应该添加到它.问题是我不能像下面那样做,因为Visual Studio说当前上下文中不存在employeeList.我怎么会写这个?

public EmployeeManager()
{
     List<string> employeeList = new List<string>();
}

public void AddEmployee()
{
     employeeList.add("Donald");
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 12

您需要使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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @user如果@Reed的帖子回答了你的问题,请将其标记为答案.它将给你们双方的声誉,让未来的人们知道哪个答案最终帮助了你. (2认同)