如何在类列表中获取属性列表?

时间:2019-11-04 09:01:49

标签: c# list class properties system.reflection

如何获取类的所有属性的列表?

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

这是我的代码,结果仅获得属性类ReqPerson,而不是类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>");
        }

有人可以改善我的代码吗?

2 个答案:

答案 0 :(得分:0)

const getLanguage = localStorage.getItem("language");
const defalutLanguage = "en";
const currentLanguage = ( getLanguage && getLanguage !== "null" 
      && getLanguage !== "undefined" ) ? getLanguage : defalutLanguage

答案 1 :(得分:0)

您可以使用反射来遍历Collection的类型。例如

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;
            }
        }
    }
}
相关问题