Cod*_*iot 2 c# reflection loops
我试图找到一种方法来循环遍历一个对象以获取对象的所有属性(它们的名称和它们的值)。我可以成功地遍历简单的属性(例如字符串、整数等...,但是当它有一个包含属性的属性时——这就是问题所在......
[ 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)));
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试完成但无法开始工作的示例代码 // 无法通过复杂的属性类型循环工作。
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人有任何想法,请告诉我。谢谢,我感谢任何反馈。
您可以根据自己的喜好重构它,但它应该可以完成基本工作。它使用一些递归来遍历复杂对象中的所有属性。它还处理可枚举的属性。
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5870 次 |
| 最近记录: |