【问题标题】:How to get the list of properties within list of a class?如何获取类列表中的属性列表?
【发布时间】:2020-02-29 13:40:12
【问题描述】:

如何获得一个类的所有属性的列表?

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

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

【问题讨论】:

  • 请出示您用来呼叫GetProperties()的代码。
  • 当你到达某个属性时,你需要检查一个集合类型,如果它是一个集合,你需要遍历它并获取这个集合元素的那些属性
  • @MatthewWatson var properties = GetProperties(object);
  • 这不可能是您的确切代码,因为object 是关键字。我知道这可能与您演示问题的一些代码相似,但重要的方面通常在于您显示的内容和正在运行的内容之间的差异。请提供minimal reproducible example,它会更容易为您提供帮助。
  • 也许退后一步,解释一下你在这里想要做什么。例如,如果一个类有一个对其自身的子引用,你会期望发生什么?你期望输出是什么?这对我来说似乎是一个 XY 问题。

标签: c# list class properties system.reflection


【解决方案1】:

您可以使用反射来迭代 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;
            }
        }
    }
}

【讨论】:

    【解决方案2】:
     public virtual ICollection<Detail> Details { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2021-03-26
      • 2014-02-27
      • 1970-01-01
      相关资源
      最近更新 更多