简体   繁体   English

获取类属性的属性

[英]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 . 第一个foreach循环工作正常,并获得类变量test的属性。 However, in the second loop, I get output such as MemberType , ReflectedType , Module etc.. not actual properties. 但是,在第二个循环中,我得到诸如MemberTypeReflectedTypeModule等的输出..而不是实际属性。

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. 在第二个循环中, GetType()返回一个PropertyInfo对象。 You have to get the propertyType of v as v.PropertyType.GetProperties() to achieve what you want. 您必须将v的propertyType作为v.PropertyType.GetProperties()来实现您想要的。

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. v.GetType()返回的类型是PropertyInfo的类型,因为v是属性信息。 You don't want the properties of the PropertyInfo type , you want the properties of the type itself. 您不需要PropertyInfo类型的属性 ,您需要类型本身的属性。

Use v.PropertyType , not v.GetType() . 使用v.PropertyType ,而不是v.GetType()

GetProperties() gets you PropertyInfo objects which tell you information about the properties of the object. GetProperties()为您提供PropertyInfo对象,告诉您有关对象属性的信息。 You need to use GetValue to actually get the values of those properties. 您需要使用GetValue来实际获取这些属性的值。 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. 编辑值后,使用SetValue将其保留回对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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