1

特定のタイプのすべてのプロパティを選択し、コンストラクタ内からデフォルト値を与える方法はありますか?

クラスにバッキング フィールドを持つ 32 個int32のプロパティがあり、コンストラクターでそれらすべてをデフォルトで -1 に設定したいのですが、コンストラクターですべてを記述する以外の方法はありますか?

4

2 に答える 2

3

少し洗練が必要かもしれませんが、このような方法でうまくいきます。

class A{
    public A()
    {
        var props = this.GetType()
                .GetProperties()
                .Where(prop => prop.PropertyType == typeof(int));
        foreach(var prop in props)
        {
            //prop.SetValue(this, -1);  //.net 4.5
            prop.SetValue(this, -1, null); //all versions of .net
        }
    }
    public int ValA{get; set;}
    public int ValB{get; set;}
    public int ValC{get; set;}
}
于 2013-10-31T20:13:25.937 に答える
1

あなたがこれをしたい場合:

void Main()
{
    var test = new Test();
    Console.WriteLine (test.X);
    Console.WriteLine (test.Y);
}

クラス定義:

 public class Test 
 {
       public int X {get; set;}
       public int Y {get; set;}

       public Test()
       {
              foreach(var prop in this.GetType().GetProperties())
              {
                    if(prop.PropertyType == typeof(int))
                    {
                          prop.SetValue(this, -1);
                    }
              }
       }
 }

出力:

-1
-1

于 2013-10-31T20:16:16.327 に答える