-3

I want to get the propertyInfo by the path that look like this:

string path = "window.position.x";

Here an example:

PropertyInfo p = typeof(WindowManager).GetProperty(path);

the WindowManager has a property called "window", which has a property called "position" which again has the property "x".

Is there some way to achieve this? Unfortunatelly GetProperty doesn't work with such a path.

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
CarpoSep
  • 35
  • 1
  • 5

3 Answers3

2

You can split your path and iterate through metadata. Try this code:

var type = typeof(WindowManager);
PropertyInfo property;
foreach (var prop in path.Split('.'))
{
    property = type.GetProperty(prop);
    if (property == null)
    {
        // log error
        break;
    }
    type = property.PropertyType;
}

// now property is x

Note that you should check property on each iteration to make sure your path is valid

Demo

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
1

You'd have to split path on the separator character (.) to get the class, property, and sub-property.

The sticky part is mapping "window" to WindowManager. You're going to need a dictionary or hash table of some sort that maps string names to known types, so that you can look them up.

Once you know the "root type", reflecting over its properties is an exercise in relatively simple reflection. For starters, I might point you to Activator.CreateInstance, GetProperties, and possibly Assembly.GetReferencedAssemblies, all of which are documented on MSDN.

Note: Your path looks like it accepts all lower case. That will be important when you're trying to map type and property names to one another.

Mike Hofer
  • 16,477
  • 11
  • 74
  • 110
0

If you're sure that path is correct, use this

string path = "window.position.x";
var pathArr = path.Split('.');
var property = typeof(WindowManager).GetProperty(pathArr[0]).PropertyType
                                    .GetProperty(pathArr[1]).PropertyType
                                    .GetProperty(pathArr[2]);
Jack Sparrow
  • 549
  • 4
  • 13