Get all properties from an object including properties of reference members

时间:2017-07-03 13:08:15

标签: c# reflection

Example:

 public class B
    {
        [IsSearchable]
        [IsEncryptable]
        public string bPropA { get; set; }
        [IsSearchable]
        [IsEncryptable]
        public string bPropB { get; set; }
    }
    class A
    {
        [IsSearchable]
        [IsEncryptable]
        public string PropA { get; set; }
        [IsSearchable]
        [IsEncryptable]
        public string PropB { get; set; }
        [IsSearchable]
        public int PropC { get; set; }
        [IsSearchable]
        public B PropD { get; set; }
    }

So out of the example above I want all 6 properties when sending an object of class A to a function. So far I've tried:

    A a = new A();
    a.GetType().GetAllProperties();

But it only returns the 4 properties and not it's members properties. Looked around but couldn't find any question regarding this matter at least not specifically.

1 个答案:

答案 0 :(得分:1)

我想你需要做类似的事情:

<强> (未测试的)

List<PropertyInfo> GetPropertiesRecursive(Type type)
{
    var properties = new List<PropertyInfo>
    foreach(var propertyInfo in type.GetProperties())
    {
        properties.Add(propertyInfo);
        if(!propertyInfo.PropertyType.IsValueType)
        {
            properties.AddRange(GetPropertiesRecursive(propertyInfo.PropertyType));
        }
    }
    return properties;
}

请注意,值类型也可以包含属性。