2016-01-30 33 views
4
using UnityEngine; 
using System.Collections; 

public class People{ 

    public string name; 
    public int type; 

} 

public class Game{ 
    public ArrayList people; 

    public void start(){ 
     People p = new People(); 
     p.name = "Vitor"; 
     p.type = 1; 

     people = new ArrayList(); 
     people.add(p); 

     Debug.Log(p[0].name); 
    } 
} 

返回錯誤:在C#中的ArrayList中的對象檢索參數?

Type 'object' does not contain a definition for 'name' and no extension method 'name' of type 'object' could be found (are you missing a using directive or an assembly reference?)

+2

如果'people'只包含「People」類型的對象,那麼最好將它聲明爲'List '而不是'ArrayList' –

+1

Ahmad說的是正確的,'ArrayList'是一個非常古老的類,並且幾乎在每種情況下都應該使用'List '。事實上,大多數人在需要時使用'List '而不是'ArrayList'。 – Kroltan

回答

4

應該Debug.Log((people[0] as People).name);

+0

謝謝,它工作完美! – SrEdredom

6

ArrayList包含的對象,所以你需要將它轉換:

Debug.Log(((People)people[0]).name); 
1

另一種方法是使用Linq:

Debug.Log(people.OfType<Person>().First().name); 

無論如何,如果有可能,你應該泛型集合,fe List<Perople>

1

ArrayList的內容始終爲object。你需要將它們轉換回你想要的類型。但要小心,仍然可以在ArrayList內部放置另一種類型的對象,如果您嘗試將其轉換爲People,則會引發錯誤。

不管怎麼說,這裏是如何投:

或全部一行(注意括號):

Debug.Log(((People) people[0]).name); 

雖這麼說,你一定要使用類型List<T>而不是ArrayList。原因是,它僅通過接受指定類型T作爲內容來保護您的代碼免受錯誤,並且當您訪問某個項目時,它已經是T類型。您的代碼,以List<People>改寫:

using UnityEngine; 
using System.Collections.Generic; 

public class People { 
    public string name; 
    public int type; 
} 

public class Game { 
    public List<People> people; 

    public void Start() { 
     People p = new People(); 
     p.name = "Vitor"; 
     p.type = 1; 

     people = new List<People>(); 
     people.Add(p); 

     Debug.Log(p[0].name); 
    } 
} 

注意,現在p[0]訪問時,就不需要投的內容。