2013-09-30 26 views
0

我一直在尋找小時,而我似乎無法找到任何答案。我試圖讓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 
} 
+0

你得到什麼錯誤? –

+0

試試'item.Info()' – paulsm4

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

2

使用item而不是listalista是集合。

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

你必須呼籲itemInfo方法,而不是在lista本身:

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

你的例子試圖運行信息()成員列表中,您想要運行列表中的某個對象的成員。 試試這個:的

item.Info(); 

代替

lista.Info(); 
相關問題