2013-09-26 94 views
1

我有一个类的属性(约30)的大数目,例如如何分配由默认值属性值属性

[DisplayName("Steps to stacker"), DefaultValue(20)] 
[Description("Value in obturator steps")] 
public int StepsToStacker { get; set; } 

[DisplayName("Enter time"), DefaultValue(120)] 
[Description("Value in milliseconds")] 
public int EnterTime { get; set; } 

有从DefaultValue atrribute实现LoadDefaultValues()其负荷值的简单方法?

+0

'DefaultValue'设计为'​​Designer'代码,用于'Components'。你必须使用反射或将其设置在构造函数 –

回答

1

虽然用途的属性是不实际设置属性的值,你可以使用反射来始终为他们无论如何。

foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this)) 
     { 
      DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)]; 

      if (myAttribute != null) 
      { 
       property.SetValue(this, myAttribute.Value); 
      } 
     } 
0

对不起,我的问题ID重复。此代码正常工作

public void LoadDefaultValues() 
{ 
    foreach (PropertyInfo p in this.GetType().GetProperties()) 
    { 
     foreach (Attribute attr in p.GetCustomAttributes(true)) 
     { 
      if (attr is DefaultValueAttribute) 
      { 
       DefaultValueAttribute dv = (DefaultValueAttribute)attr; 
       p.SetValue(this, dv.Value, null); 
      } 
     } 
    } 
} 
+0

那我的答案呢? –