特定のタイプのすべてのプロパティを選択し、コンストラクタ内からデフォルト値を与える方法はありますか?
クラスにバッキング フィールドを持つ 32 個int32
のプロパティがあり、コンストラクターでそれらすべてをデフォルトで -1 に設定したいのですが、コンストラクターですべてを記述する以外の方法はありますか?
特定のタイプのすべてのプロパティを選択し、コンストラクタ内からデフォルト値を与える方法はありますか?
クラスにバッキング フィールドを持つ 32 個int32
のプロパティがあり、コンストラクターでそれらすべてをデフォルトで -1 に設定したいのですが、コンストラクターですべてを記述する以外の方法はありますか?
少し洗練が必要かもしれませんが、このような方法でうまくいきます。
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;}
}
あなたがこれをしたい場合:
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