【问题标题】:C# Loop/Iterate through object to get property values with complex property typesC#循环/迭代对象以获取具有复杂属性类型的属性值
【发布时间】:2021-09-16 23:56:10
【问题描述】:

我正在尝试找到一种方法来循环和迭代对象以获取对象的所有属性(它们的名称和值)。我可以成功地遍历简单的属性(例如字符串、int 等……,但是当它有一个包含属性的属性时——这就是问题所在……

[ Working for Simple string/int/bool properties ], but I need something that will work with nested / complex property types.

            foreach (PropertyInfo spotProperties in spot.GetType().GetProperties())
            {
                // Simple property type (string, int, etc...)  add the property and its value to the node.
                var attributeName = spotProperties.Name; 
                resultElement.Add(new XElement(attributeName, spotProperties.GetValue(spot, null)));
            }

我正在尝试完成但无法开始工作的示例代码 // 无法通过复杂的属性类型进入工作循环。

            foreach (PropertyInfo spotProperties in spot.GetType().GetProperties())
            {
                if (--spotProperties is complex type then --)
                {
                    // The item is a complex data type, and needs to have it's properties iterated and added to the node.
                    foreach (PropertyInfo childSpotProperty in spotProperties.GetValue(spot, null).GetType().GetProperties())
                    {
                        var attributeName = ((DisplayNameAttribute)childSpotProperty.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault() as DisplayNameAttribute)?.DisplayName ?? childSpotProperty.Name;
                        //resultElement.Add(new XElement(attributeName, childSpotProperty.GetValue(childSpotProperty, null)));
                    }
                }
                else
                {
                    // Simple property type (string, int, etc...)  add the property and its value to the node.
                    var attributeName = spotProperties.Name;
                    resultElement.Add(new XElement(attributeName, spotProperties.GetValue(spot, null
                }
            }

如果有人有任何想法,请告诉我。谢谢,感谢任何反馈。

【问题讨论】:

  • 这个SO 问题?
  • 好吧,首先考虑一下你是否真的要为此使用反射;在某些情况下,反射可能会很慢。此外,从您显示的代码来看,您似乎正在尝试对 XML 进行序列化和反对。 .NET 中有用于此的库——研究 XmlSerializer。也就是说,您需要考虑编写递归函数。

标签: c# loops reflection


【解决方案1】:

您可以根据自己的喜好对其进行重构,但它应该可以完成基本工作。它使用一些递归来遍历复杂对象中的所有属性。它还处理可枚举的属性。

public class PropertyInformation
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<PropertyInformation> ObjectPropertyInformation(object obj)
{
    var propertyInformations = new List<PropertyInformation>();

     foreach (var property in obj.GetType().GetProperties())
    {
        //for value types
        if (property.PropertyType.IsPrimitive || property.PropertyType.IsValueType || property.PropertyType == typeof(string))
        {
            propertyInformations.Add(new PropertyInformation { Name = property.Name, Value = property.GetValue(obj) });
        }
        //for complex types
        else if (property.PropertyType.IsClass && !typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
        {
            propertyInformations.AddRange(ObjectPropertyInformation(property.GetValue(obj)));
        }
        //for Enumerables
        else
        {
            var enumerablePropObj1 = property.GetValue(obj) as IEnumerable;

            if (enumerablePropObj1 == null) continue;

            var objList = enumerablePropObj1.GetEnumerator();

            while (objList.MoveNext())
            {
                objList.MoveNext();
                ObjectPropertyInformation(objList.Current);
            }
        }
    }

    return propertyInformations;
}

【讨论】:

    【解决方案2】:

    这可行,但它确实有一个错误。

    修复如下所示:

    //for Enumerables
    else
    {
        var enumerablePropObj1 = property.GetValue(obj) as IEnumerable;
    
        if (enumerablePropObj1 == null) continue;
    
        var objList = enumerablePropObj1.GetEnumerator();
    
        while (objList.MoveNext())
        {
    ==         if(objList.Current != null)
    ==         {
    ==             propertyInformations.AddRange(ObjectPropertyInformation(objList.Current));
    ==         }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多