简体   繁体   English

如何获取 class 列表中的属性列表?

[英]How to get the list of properties within list of a class?

How do I get a list of all the properties of a class?如何获取 class 的所有属性的列表?

public class ReqPerson
{
    public String Name { get; set; }
    public String Age { get; set; }
    public List<Detail> Details { get; set; }
}

public class Detail
{
    public String Job { get; set; }
    public String City { get; set; }
}

This is my code, and the result only get properties class ReqPerson, not for class Detail.这是我的代码,结果只获取属性 class ReqPerson,而不是 class 详细信息。

 private static PropertyInfo[] GetProperties(object obj)
    {
        return obj.GetType().GetProperties();
    }

       ReqPerson req = new ReqPerson();
        // Get property array
        var properties = GetProperties(req);

        foreach (var p in properties)
        {
            string name = p.Name;
            var value = p.GetValue(Inq.ReqInquiry(req, null);
            Response.Write(name);
            Response.Write("</br>");
        }

Anybody can improve my code?有人可以改进我的代码吗?

 public virtual ICollection<Detail> Details { get; set; }

You could use reflection to iterate over the type of Collection.您可以使用反射来迭代 Collection 的类型。 For example例如

private IEnumerable<PropertyInfo> GetProperties(Type type)
{
    PropertyInfo[] properties = type.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        if ( property.PropertyType.GetInterfaces()
               .Any(x => x == typeof(IList)))
        {
             foreach(var prop in GetProperties(property.PropertyType.GetGenericArguments()[0]))
                yield return prop;
        }
        else
        {
            if (property.PropertyType.Assembly == type.Assembly)
            {
                if (property.PropertyType.IsClass)
                {
                    yield return property;
                }
                GetProperties(property.PropertyType);
            }
            else
            {
                yield return property;
            }
        }
    }
}

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

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