我一直試圖使用foreach
遍歷對象的List
,似乎無法得到正確的語法。這是一個簡單的例子。C#正確的foreach語法迭代列表
class foo
{
private int x = 1;
public foo(int y)
{
x = y;
}
public int X
{
get { return x; }
}
}
class bar
{
foo footest = new foo(3);
private List<foo> myfoo = new List<foo>();
public bar()
{
for (int i = 0; i < 3; i++)
{
myfoo.Add(footest);
}
}
/*Below is what I can't seem to get working. I want to write a method
that iterates through the list of foo objects and displays a property for
each one. The compiler gives an error under foreach that says "A get or
set accessor expected."
/*public void getall
{
foreach (bar Myfoo in myfoo) //error under foreach
{
Console.Write(Myfoo.X);
}*/
}
'foreach(var myfoo in myfoo)'? – Uriil