【发布时间】: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