2017-05-24 1 views
1

문자열이 포함 된 개체와 문자열이 포함 된 개체가 있습니다. 개체와 하위 개체에 null 값이 아닌 빈 문자열이 있는지 확인해야합니다. 지금까지이 잘 작동합니다 :모든 null 개체 매개 변수를 string.empty로 설정하십시오.

foreach (PropertyInfo prop in contact.GetType().GetProperties()) 
{ 
    if(prop.GetValue(contact, null) == null) 
    { 
     prop.SetValue(contact, string.empty); 
    } 
} 

문제는 문자열을 하위 개체이 개체 만 문자열에 대한 작품이 아니다. null 인 경우 모든 하위 객체를 반복하고 해당 문자열을 string.Empty으로 설정할 수 있습니까?

다음은 '접촉'개체의 예 :

new contact 
{ 
    a = "", 
    b = "", 
    c = "" 
    new contact_sub1 
    { 
    1 = "", 
    2 = "", 
    3 = "" 
    }, 
    d = "" 
} 

는 기본적으로 나는 또한 널 위해 contact_sub1에서 확인하거나 빈 string으로 값을 교체해야합니다.

+2

같은 접근 방식이지만 재귀 적으로 –

+2

"하위 개체"도 재귀를 사용하여 처리하십시오. – Abion47

답변

1

현재 코드를 수정하여 모든 하위 개체를 가져온 다음 null 문자열 속성에 대해 동일한 검사를 수행 할 수 있습니다.

public void SetNullPropertiesToEmptyString(object root) { 
    var queue = new Queue<object>(); 
    queue.Enqueue(root); 
    while (queue.Count > 0) { 
     var current = queue.Dequeue(); 
     foreach (var property in current.GetType().GetProperties()) { 
      var propertyType = property.PropertyType; 
      var value = property.GetValue(current, null); 
      if (propertyType == typeof(string) && value == null) { 
       property.SetValue(current, string.Empty); 
      } else if (propertyType.IsClass && value != null && value != current && !queue.Contains(value)) { 
       queue.Enqueue(value); 
      } 
     } 
    } 
} 
관련 문제