2010-11-27 12 views
7

私はC#の新機能です。オブジェクトのプロパティを反復処理し、すべての空文字列を ""に設定する関数を記述したいと思います。私はそれが "リフレクション"と呼ばれるものを使用して可能であると聞いたことがありますが、私は方法がわかりません。C#でオブジェクトのすべてのプロパティを反復処理する方法は?

おかげ

+2

を参照してください。私はあなたがそれで達成しようとしていることを知りたいのですか? – andynormancx

+0

メモでは、null文字列を ""ではなく "String.Empty"に設定することを検討することをお勧めします。実際の影響は無視できるものですが、効率的なコードのために、前者は新しいオブジェクトを作成しません。 – Cranialsurge

+0

また、私はandynormancxと同意します....あなたの目的は何ですか? – Cranialsurge

答えて

19
public class Foo 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
    public int Prop3 { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var foo = new Foo(); 

     // Use reflection to get all string properties 
     // that have getters and setters 
     var properties = from p in typeof(Foo).GetProperties() 
         where p.PropertyType == typeof(string) && 
           p.CanRead && 
           p.CanWrite 
         select p; 

     foreach (var property in properties) 
     { 
      var value = (string)property.GetValue(foo, null); 
      if (value == null) 
      { 
       property.SetValue(foo, string.Empty, null); 
      } 
     } 

     // at this stage foo should no longer have null string properties 
    } 
} 
+2

+1の読み取り/書き込みのチェック – Aliostad

+3

はい、読み取り/書き込みのチェックは読み取り/書き込みの前に重要です。 –

+0

あなたの答えをありがとう。 – Ristovak

1
foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public)) 
{ 
    if (pi.GetValue(myobject)==null) 
    { 
     // do something 
    } 
} 
関連する問題