简体   繁体   中英

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?

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.

 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. 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;
            }
        }
    }
}

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