1

有没有办法选择特定类型的所有属性并从构造函数内部给它一个默认值?

int32在一个类中有 32 个带有支持字段的属性,我想在构造函数中将它们全部默认为 -1,除了将它们全部写入构造函数之外还有什么其他方法吗?

4

2 回答 2

3

Might take a bit of refinement, but something like this would do the trick.

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 回答