我正在学习 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/