2016-07-27 2 views
0

현재 내 개체의 값을 내고 있습니다. 그들 중 일부는 ToString() 메서드를 사용하여 문제를 일으키는 List<string> 속성이 있습니다. 다음은 기본 클래스에서 속성의 이름과 값을 문자열로 가져 오는 데 사용하는 코드입니다.속성이 C#의 리플렉션을 사용하여 목록인지 확인합니다.

public override string ToString() 
    { 
     string content = ""; 
     foreach (var prop in this.GetType().GetProperties()) 
     { 
      if (prop.PropertyType is IList<string> && prop.GetType().IsGenericType && prop.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) 
       content += prop.Name + " = " + PrintList((List<string>)prop.GetValue(this)); 
      else 
      content += prop.Name + " = " + prop.GetValue(this) + "\r\n"; 
     } 
     content += "\r\n"; 
     return content; 
    } 

    private string PrintList(List<string> list) 
    { 
     string content = "["; 
     int i = 0; 
     foreach (string element in list) 
     { 
      content += element; 
      if (i == list.Count) 
       content += "]"; 
      else 
       content += ", "; 
     } 
     return content; 
    } 

아무튼, 속성이 목록인지 확인하지 않습니다. 이것은 멍청한 질문 일 수도 있고 반성과 함께 일하는 나쁜 방법 일 수도 있지만, 나는 그것에 익숙하지 않고 어떤 일이 일어나고 있는지를 이해하는 데 도움이 될 것입니다.

+0

시도인가를 IEnumerable – Steve

+4

'prop.PropertyType.IsAssignableFrom (대해서 typeof (IList의 ))' – Nkosi

답변

1
public override string ToString() 
{ 
    StringBuilder content = new StringBuilder(); 
    foreach (var prop in this.GetType().GetProperties()) 
    { 
     var propertyType = prop.PropertyType; 
     var propertyValue = prop.GetValue(this); 
     if (propertyValue != null) 
     { 
      if (propertyValue is IEnumerable<string>) 
       content.AppendFormat("{0} = {1}", prop.Name, PrintList(propertyValue as IEnumerable<string>)); 
      else 
       content.AppendFormat("{0} = {1}", prop.Name, propertyValue.ToString()); 
     } 
     else 
      content.AppendFormat("{0} = null", prop.Name); 
     content.AppendLine(); 
    } 

    return content.ToString(); 
} 

private string PrintList(IEnumerable<string> list) 
{ 
    var content = string.Join(",", list.Select(i => string.Format("[{0}]", i))); 
    return content; 
} 
+0

완벽하게 작동합니다! 감사. –

1

나는 이것을 할 것이다. 대신 + 연산자 concatenatings 스트링 또한

var property = prop.GetValue(this); 

// try to cast as IEnumerable<string> -- will set to null if it's not. 
var propertyStrings = property as IEnumerable<string>; 
if (propertyStrings != null) { 
    foreach(var s in propertyStrings) { 
     // do something here with your strings.  
    } 
} 

는, 메모리 속도 및 더 StringBuilder 살펴 취.

+0

내가'string's에'+ = '사용의 비 효율성을 볼 수 있지만, 왜'+'나쁜 것입니까? – Downvoter

+0

@Downvoter + =와 동일합니다. a = b + c를하기 위해서, 문자열'b + c'를 메모리에 할당 한 다음,에 할당해야합니다. 1M 스트링을 추가하려면 1M 스트링 할당이 필요하며 매번 그렇게 할 때마다 결과는 점점 더 커지면서 할당량은 점점 더 비싸집니다. 모든 문자열이's' 문자가 길면 O (s + 2s + 3s + 4s + 5s + 6s ... 1000000s)가 추가됩니다. O (s.n^2)라고 생각합니다. StringBuilder는 메모리가 부족한 경우 배열을 두 배로 늘리므로 모든 문자열에 O (s)와 O (s.n)를 추가합니다. –

+0

'StringBuilder' 힌트를 가져 주셔서 감사합니다! @ 스티브 쿠퍼 –

관련 문제