C# 遍历构造函数中的属性
是否有一种方法可以选择特定类型的所有属性,并从构造函数内部为其提供默认值C# 遍历构造函数中的属性,c#,C#,是否有一种方法可以选择特定类型的所有属性,并从构造函数内部为其提供默认值 我在一个类中有32个带有支持字段的int32属性,我想在构造函数中将它们全部默认为-1,除了在构造函数中写入它们之外,还有其他方法吗?可能需要一些细化,但类似这样的方法就可以了 class A{ public A() { var props = this.GetType() .GetProperties() .Where(pro
我在一个类中有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;}
}
可能需要一点改进,但像这样的东西就可以了
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-一,
如果要执行此操作,请执行以下操作:
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-一,
您可以直接将默认值设置为backing字段:
private int\u myField=-1你确定在一个类中有32个属性是有意义的吗?这通常是一个迹象,表明将它们分成更小的类型是值得的。你能举例说明这些属性的含义吗?@MarcinJuraszek:当然,如果它们是自动实现的属性,那就不起作用了。我在这里是@JonSkeet——如果这些字段相关,可能是这些字段的集合?@JonSkeet他说,他有带支持字段的属性@user1492051:但您的问题表明,您已经拥有所有这些支持字段,因此只需将=-1
添加到声明中即可。您可以直接将默认值设置为支持字段:private int\u myField=-1你确定在一个类中有32个属性是有意义的吗?这通常是一个迹象,表明将它们分成更小的类型是值得的。你能举例说明这些属性的含义吗?@MarcinJuraszek:当然,如果它们是自动实现的属性,那就不起作用了。我在这里是@JonSkeet——如果这些字段相关,可能是这些字段的集合?@JonSkeet他说,他有带支持字段的属性@user1492051:但你的问题是,你已经有了所有这些支持字段,所以只需要将=-1
添加到声明中。也许this.GetType().GetProperties().Where(p=>p.PropertyType==typeof(int))
所以不要害怕添加其他属性?@Ilyavanov:是的。p=>p.PropertyType==typeof(int)&&p.CanWritemy方法有一个缺点:long
和float
属性将被忽略,这可能是不需要的。在完美的文字中,您可以编写new[]{typeof(int)、typeof(decimal)、typeof(long)}.Contains(prop.PropertyType)
@plinth这很快就会成为一个凌乱的linq索引,可能this.GetType().GetProperties().Where(p=>p.PropertyType==typeof(int))
所以不要害怕添加其他属性?@IlyaIvanov:的确如此。p=>p.PropertyType==typeof(int)和&p.CanWritemy方法有一个缺点:long
和float
属性将被忽略,这可能是不需要的。用一个完美的词,您可以编写new[]{typeof(int)、typeof(decimal)、typeof(long)}.Contains(prop.PropertyType)
@plinth这很快就会变成一个凌乱的linq