jeudi 25 octobre 2018

In C#, Generically get the property value within a List object

I have a Match object structured as,

class Match
{
    public string location { get; set; }
    public List<Team> teams { get; set; }
    public Match()
    {
        location = "Wembley";
        teams = new List<Team>();
        teams.Add(new Team("Arsenal"));
        teams.Add(new Team("Burnley"));
    }
}
public class Team
{
    public string name { get; set; }
    public int score { get; set; }
    public Team(string title)
    {
        name = title;
        score = 0;
    }
}

I use a helper class to get the value,

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null :  T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

I am planning to allow the user to set values by typing them in a GUI as "match.team[1].name" for example and then split this to a parameter call such as in this code; this may go down several layers. Here we go down a layer to get a property value from a member of the list,

int teamNo = 1;
MessageBox.Show(GetSubProperty(match, "teams", teamNo, "name")); 

My routine is this,

    private string GetSubProperty(object obj, string prop1, int whichItem,  string prop2)
    {
        var o = obj.GetPropertyValue(prop1);
        object subObject = ((List<Team>)o)[whichItem];
        return subObject.GetPropertyValue(prop2).ToString();
    }

When getting a property in one of the Team List objects, I have to cast the value to List before accessing the individual item in the list. I wanted to know how I could do this generically for any object type being sent in. I tried List and ArrayList and quite a few other variations but am getting an error" Unable to cast object of type 'System.Collections.Generic.List1[quickTest.Classes.Team]' to type 'System.Collections.Generic.List1[System.Object]"





Aucun commentaire:

Enregistrer un commentaire