0

I have been searching for hours and I just can't seem to find any kind of answers. I'm trying to make foreach loop use a method inside of my object. Hopefully you can understand and help me.

Warrior.cs:

public void Info()
{
    Console.WriteLine("N: "
                      + this.name
                      + ", L: "
                      + this.level
                      + ", H: "
                      + this.health
                      + ", D: "
                      + this.damage
                      + ", A: "
                      + this.agility);
}

Program.cs:

List<Warrior> lista = new List<Warrior>();

for (int i = 0; i < 10; i++)
{
    lista.Add(new Warrior("Swordman" + i.ToString()));
}

foreach (Warrior item in lista)
{
    lista.Info();//<----------This is where I get the error
}
4

4 回答 4

3

项目的实例存储在 中item,而不是lista

foreach (Warrior item in lista)
{
    item.Info();
}

forach 从 调用 GetEnumerator()并存储in的lista每个元素。listaitem

在这里查看更多信息:foreach,在 http://msdn.microsoft.com/en-us/library/ttw7t8t6(v=vs.71).aspx

于 2013-09-30T20:02:16.560 回答
2

您的示例正在尝试运行 LIST 的 Info() 成员,您希望在其中运行列表中对象之一的成员。尝试这个:

item.Info();

代替

lista.Info();
于 2013-09-30T20:04:39.003 回答
2

item而不用listalista是集合。

    foreach (Warrior item in lista)
    {
        item.Info();//<----------This is where i get the error
    }
于 2013-09-30T20:02:14.297 回答
2

您必须调用Info方法 on item,而不是调用方法lista本身:

foreach (Warrior item in lista)
{
    item.Info();//
}
于 2013-09-30T20:02:27.533 回答