2016-06-15 2 views
2

루프를 반복하여 객체를 반복하여 객체의 모든 속성 (이름과 값)을 가져 오려고합니다. 나는 성공적 등 문자열, 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 
       } 
      } 

내가 다시 어떤 사료를 주셔서 감사합니다, 사람이 어떤 생각. 감사가 있으면 알려 주시기 바랍니다.

+0

이 [SO (http://stackoverflow.com/questions/863881/how-do-i-tell-if-a-type-is-a-simple-type-ie-holds-a - 단 하나 가치) 질문? –

+1

글쎄, 먼저 이것을 반영하기 위해 리플렉션을 사용하고 싶은지 고려해보십시오. 반사는 어떤 상황에서는 상당히 느릴 수 있습니다. 또한 표시하는 코드에서 XML로 직렬화하고 객체화하려는 것처럼 보입니다. .NET에는 그 라이브러리를위한 XmlSerializer가 있습니다. 즉, 재귀 함수를 작성해야합니다. –

답변

2

원하는대로 리팩터링 할 수 있습니다. 그러나 기본적인 일을 끝내야합니다. 그것은 복잡한 객체의 모든 속성을 통해 이동하기 위해 재귀를 사용합니다. Enumerable 인 속성도 처리합니다.

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

훌륭한 솔루션, 빠른 응답을 주셔서 대단히 감사드립니다. 위대한 작품! – CodingRiot

+0

1 1/2 년 후의 downvote? 왜 그런가? –

관련 문제