【问题标题】:Method from an object in a list来自列表中对象的方法
【发布时间】:2013-10-06 19:39:27
【问题描述】:

我已经搜索了好几个小时,但似乎找不到任何答案。我试图让foreach 循环在我的对象内部使用一种方法。希望您能理解并帮助我。

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
}

【问题讨论】:

标签: c# class object foreach


【解决方案1】:

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

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

forach 从lista 调用GetEnumerator() 并将lista 的每个元素存储在item 中。

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

【讨论】:

    【解决方案2】:

    使用item 而不是listalista 是集合。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        item.Info();
        

        而不是

        lista.Info();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-07-19
          • 2015-12-09
          • 2017-09-24
          • 2019-09-20
          • 1970-01-01
          • 1970-01-01
          • 2012-08-07
          相关资源
          最近更新 更多