2016-07-27 3 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

試みは、私は+ = '' string'sに '使用して非効率性を参照してください – 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

私はこれを行います。

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.  
    } 
} 

また、代わりに+オペレータとconcatenatings列で、メモリと速度のために優れている、StringBuilderを見てみましょう。

+0

IEnumerableをされていますが、なぜ、' + '悪いのでしょうか? – Downvoter

+0

@Downvoter + =と同じです。 a = b + cを行うには、文字列 'b + c'をメモリに割り当ててから、に代入する必要があります。たとえば、1Mの文字列を追加するには、1Mの文字列の割り当てが必要です。そのたびに、結果はますます大きくなります。すべての文字列が 's' chars長い場合、追加はO(s + 2s + 3s + 4s + 5s + 6s ... 1000000s)です。私はそれがO(s.n^2)だと思う。 StringBuilderはメモリが不足したときに配列を倍増させるので、文字列を追加するにはO(s)、すべての文字列にO(s.n)を追加します。 –

+0

'StringBuilder'ヒントをありがとう! @SteveCooper –

関連する問題