c# - 如何添加到尚未创建的列表。请帮忙!

标签 c# list

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

管理器类有一个构造函数和一个方法(见下文)。 构造函数创建 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/

相关文章:

c# - NancyFX 无法识别自定义数据注释

c# - 如何访问有关 WCF 服务部署位置的信息

c# - MVC 3 多表单模型传递给字典

r - 列表中最长元素的长度

list - mapMaybes/catMaybe 在 Windows 和 Ubuntu 中的工作方式不同

java - 具有要在 Excel 中显示的不同数据的列表

java - 如何用 "@"替换所有空行?

c# - 将 ASP.net MVC2 升级到 MVC4 Razor View 智能感知不起作用

C# 查找相关文档片段用于搜索结果显示

c++ - C++ 中的字符串变量参数列表