Getting parameter in object inside ArrayList in C #?

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);
    }
}

Error returned:

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

+4
source share
4 answers

ArrayList consists of objects, so you need to cast it:

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

He must be Debug.Log((people[0] as People).name);.

+4
source

Linq:

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

, , , .. List<Perople>.

+1

ArrayList object. , . , ArrayList, People, .

, :

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

( ):

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

With that said, you should use a type List<T>instead ArrayList. Of course, it protects your code from errors only by accepting the specified type Tas content, and when you access an element, it already has a type T. Your code rewritten with 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);
    }
}

Note that now you do not need to highlight content when accessing with p[0].

+1
source

Source: https://habr.com/ru/post/1626692/


All Articles