c# 如何修复 foreach ,当我尝试 console.write 列表中的元素 <string>

标签 c# list foreach

我正在学习 C#,我的代码有一些问题。我不知道为什么我不能在示例中使用 foreach。我该怎么做才能解决这个问题?有什么建议吗?

  public class Company
  {
    List<string> workers;
    public Company()
    {
        workers= new List<string>();
    }
    public void AddWorker(string x)
    {
        workers.Add(x);
    }
  }

    static void Main(string[] args)
    {
        Company c1= new Company();
        c1.AddWorker("Adam Snow");
        c1.AddWorker("John Big");
        c1.AddWorker("Chris Zen");

        foreach (var x in c1)
        {
            Console.WriteLine(x);
        }
     }

最佳答案

在行中

foreach (var x in c1)

您尝试遍历不可枚举的 Company 实例。您想要遍历该实例的 workers 列表。

一个解决方案是让 workers 成为公共(public)属性(property):

public class Company
{
    List<string> workers;
    public IEnumerable<string> Workers { get { return workers; } }

    // shortened for brevity
}

然后你可以像那样使用foreach:

foreach (var x in c1.Workers) // <- access the Workers property here
{
    Console.WriteLine(x);
}

正如 Dmitry 所建议的,您可能希望只将 workers 列表公开为只读,以便该类的用户无法从外部更改列表的内容:

public class Company
{
    List<string> workers;
    public IReadOnlyCollection<string> Workers
    { 
        get { return workers.AsReadOnly(); }
    }

    // shortened for brevity
}

关于c# 如何修复 foreach ,当我尝试 console.write 列表中的元素 <string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001536/

相关文章:

c# - 如何在 Windows 10 应用中实现应用内购买?

c# - 按 ID 的 BinarySearch 对象数组

python - 类型错误:只能将列表(不是 "int")连接到列表 4

c++ - 为什么从 C++11 中删除了对范围访问?

javascript - 如何在javascript中创建一个对象的foreach?

c# - 为什么 datatable.Clear 也清除其他数据表?

c# - 使用 IPageRouteModelConvention 时获取版本

Python:使用列表列表读取CSV文件的字段

c# - 比较两个列表并返回共同条目

c# - foreach 语句给出错误