简体   繁体   English

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

[英]c# how to fix foreach , when i try to console.write elements in my list<string>

I am learning c# and i have some problem with my code. 我正在学习c#,我的代码有问题。 I have no idea why i cant use foreach in my example . 我不知道为什么我不能在我的例子中使用foreach。 What can i do to fix this problem? 我该怎么做才能解决这个问题? Any suggestions? 有什么建议么?

  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);
        }
     }

In the line 在线

foreach (var x in c1)

you try to iterate over your instance of Company which is not enumerable. 您尝试迭代不可枚举的Company实例。 You want to iterate over the workers list of that instance. 您想要遍历该实例的workers列表。

One solution is to make workers a public property: 一个解决方案是让workers成为公共财产:

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

    // shortened for brevity
}

and then you can use foreach like that: 然后你就可以像这样使用foreach

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

As Dmitry suggested, you may want to expose the workers list only as readonly, so that users of that class cannot change the list's content from outside: 正如Dmitry建议的那样,您可能只希望将worker列表公开为readonly,以便该类的用户无法从外部更改列表的内容:

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

    // shortened for brevity
}

If you want iterate over Company class instance, Company has to implement IEnumerable<string> : 如果要迭代Company类实例, Company必须实现IEnumerable<string>

public class Company : IEnumerable<string>{
  ...
  public IEnumerator<string> GetEnumerator() {
    return workers.GetEnumerator();
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return workers.GetEnumerator();
  }
}

having done this you can put 这样做你可以放

Company c1 = new Company();

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

do workers list public and loop in c1.workers then it's ok. 工人列出公共和循环c1.workers然后它没关系。

public List<string> workers;

then 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM