vendredi 26 février 2016

Get me object property using a string

I have seen several examples of reflection on here but cant seem to get them to work for my exact issue...

example of a solution I looked at

My 3 classes...

 public class Row
    {
        public string Cell1  = "cat";//{ get; set; }
        public string Cell2 = "fish"; //{ get; set; }
        public string Cell3 = "dog";  //{ get; set; }


    }

    public class Grid
    {
        public Row Row1 = new Row();
        public Row Row2 = new Row();
        public Row Row3 = new Row();

    }

    public class SetOfGrids
    {
        public Grid g1 = new Grid();
        public Grid g2 = new Grid();
    }

How I can get the value...

SetOfGrids sog = new SetOfGrids();
 MessageBox.Show(sog.g1.Row1.Cell1);

The getproperty function for the link i thought might work...

public Object GetPropValue(String name, Object obj) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

How I would like to get the value... (I get a null exception error.)

 string PathToProperty = "sog.g1.Row1.Cell1";
 string s = GetPropValue("sog.g1.Row1.Cell1", sog).ToString;
 MessageBox.Show(s);

Result should be "cat2"





Aucun commentaire:

Enregistrer un commentaire