我试图找到一种方法来遍历并遍历一个对象,以获取对象的所有属性(它们的名称和值)。我可以成功地遍历简单属性(例如字符串,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
}
}
如果有人有任何想法,请告诉我。谢谢,我感谢任何反馈。
答案 0 :(得分:3)
你可以根据自己的喜好对其进行重构,但它应该完成基本的工作。它使用一些递归来遍历复杂对象中的所有属性。它还处理可枚举的属性。
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;
}
答案 1 :(得分:0)
这就像一个冠军,但它确实有一个错误(也许为什么不投票?)
修复如下所示:
//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));
== }
}