简体   繁体   中英

Get properties of properties of a class

I want to get the properties of the properties of a class.

What I have right now:

foreach (var v in test.GetType().GetProperties())
{
    foreach (var p in v.GetType().GetProperties())
    {
    }
}

The first foreach loop works fine and gets the properties of the class variable test . However, in the second loop, I get output such as MemberType , ReflectedType , Module etc.. not actual properties.

My goal is to get the properties of the properties of a class and then edit their value (truncate them using another function).

Thanks.

On the second loop GetType() returns a PropertyInfo object. You have to get the propertyType of v as v.PropertyType.GetProperties() to achieve what you want.

So, the code should be:

foreach (var v in test.GetType().GetProperties())
{
    foreach (var p in v.PropertyType.GetProperties())
    {
        // Stuff
    }
}

The type returned by v.GetType() is that of PropertyInfo, because v is a property info. You don't want the properties of the PropertyInfo type , you want the properties of the type itself.

Use v.PropertyType , not v.GetType() .

GetProperties() gets you PropertyInfo objects which tell you information about the properties of the object. You need to use GetValue to actually get the values of those properties. From there you can repeat the process to get the values of that object's properties.

foreach (var v in test.GetType().GetProperties())
{
    var propertyValue = v.GetValue(test);
    foreach (var p in propertyValue.GetType().GetProperties())
    {
        var subPropertyValue = p.GetValue(propertyValue);
        Console.WriteLine("{0} = {1}", p.Name, subPropertyValue);
    }
}

After editing the value use SetValue to persist it back to the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM