mercredi 26 mai 2021

How to get the specified value from a List

Let's say if we have a Container class with generic array

public class Container<T>
{
    public T[] ObjectArray = new T[];
}

public class PlayerInfo
{
    public int level;
    public string playerName;
    public string description
}

public class EnemyInfo
{
    public string enemyName;
}

Now I have Container<PlayerInfo> and Container<EnemyInfo> in my app, which have lots of player/enemy data.

I want to create a List to handle all Container in my app, and print out all fields with string type, how could I achieve it?

Take the above example I want to print out playerName description enemyName.

What I've tried is like this.

//let container inherit from a class
public class Container<T> : BaseClass
{
    public T[] ObjectArray = new T[];
}

//so that I could add them to a single list.
var list = new List<BaseClass>();
list.Add(playerContainerInstance);
list.Add(enemyContainerInstance);

foreach(var element in list)
{
    //and what should I do now to get string field from it?
}

For now I can figure out is do something with reflection, but maybe there is another way to do this?





Aucun commentaire:

Enregistrer un commentaire