mardi 21 avril 2015

Get type of a property from nested class

I have the following classes:

class TopClass
{
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

class SubClass
{
    public string SCProp1 { get; set; }
    public string SCProp2 { get; set; }
}

When I write the following code to return the property type of one of the members it works fine:

System.Reflection.PropertyInfo p = typeof(TopClass).GetProperty("ClsProp1");
Type t = p.PropertyType;

But how do I recursively check the type of the field inside the nested SubClass by name.. I could write a loop that parses the string I need into tokens on the '.' but this seems to have a "code smell" that isn't very elegant. Ultimately what I'd like to do is something like this:

System.Reflection.PropertyInfo p = typeof(TopClass).GetProperty("ClsProp3.SCProp1");
Type t = p.PropertyType;

But I have no idea how to implement that without complicated looping code.

Thanks in advance





Aucun commentaire:

Enregistrer un commentaire