dimanche 17 juillet 2016

Use reflection "GetValue" to return information from Dictionary

I am trying to use reflection to get values from objects. I use reflection to load a class and all its properties and fields into a treeview. When I click on a treenode, I use the tree hierarchy to generate a "path", which I can then feed into a function that gets the property value.

I borrowed code heavily from this link, but am struggling with one part: How to get the properties when one of the objects in the tree is a dictionary.

Code as follows:

 public object GetPropertyValueFromPath(object baseObject, string path)
    {
        //Split into the base path elements
        string[] pp = CorrectPathForDictionaries(path).Split(new[]{ '.' }, StringSplitOptions.RemoveEmptyEntries);

        object valueObject = null;            
        Type t = baseObject.GetType();
        foreach (var prop in pp)
        {
            PropertyInfo propInfo = t.GetProperty(prop);
            if (propInfo != null)
            {
                valueObject = propInfo.GetValue(baseObject, null);
                t = propInfo.PropertyType;
            }
            else
            {
                //System.Diagnostics.Debug.WriteLine("Path does not point to valid object");
                return "Path does not point to valid object";

            }
        }
        return valueObject;
    }

An example of what I am trying to do would be:

BaseClass

  1. Property double: TotalCapacity=35
  2. Property double: UsableCapacity=30
  3. Property (Class): Sensitivity
  4. Property (Dictionary[Sensitivity]) Scenarios

Scenario Class

  1. Property double ModifiedCapacity=25
  2. Property double ModifiedUsableCapacity=20

If I call the above with the path as "TotalCapacity", I get 35. If I call the above with the path as "Sensitivity.ModifiedCapacity", I get 25.

All this works fine.

What I want to be able to do is pass (for example) a path being "Scenario[3].ModifiedCapacity" (Scenario is a dictionary of "Sensitivity" objects).

How can I do this? In short: How to I use GetValue to return a value from a dictionary from its "path"?





Aucun commentaire:

Enregistrer un commentaire