루프를 반복하여 객체를 반복하여 객체의 모든 속성 (이름과 값)을 가져 오려고합니다. 나는 성공적 등 문자열, INT, 같은 간단한 속성 (반복 할 수 있지만, 그것은 속성이 포함 된 재산이있는 경우 -의 문제가 어디에 즉 ...C# 복잡한 속성 유형을 사용하여 속성 값을 얻기 위해 객체를 반복/반복합니다.
[ 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 (http://stackoverflow.com/questions/863881/how-do-i-tell-if-a-type-is-a-simple-type-ie-holds-a - 단 하나 가치) 질문? –
글쎄, 먼저 이것을 반영하기 위해 리플렉션을 사용하고 싶은지 고려해보십시오. 반사는 어떤 상황에서는 상당히 느릴 수 있습니다. 또한 표시하는 코드에서 XML로 직렬화하고 객체화하려는 것처럼 보입니다. .NET에는 그 라이브러리를위한 XmlSerializer가 있습니다. 즉, 재귀 함수를 작성해야합니다. –