属性上的.Net DefaultValueAttribute

我在用户控件中得到了这段代码:

[DefaultValue(typeof(Color), "Red")] public Color MyColor { get; set; } 

如何将MyColor更改为默认值?

它是非正式的,但您可以通过reflection使用它,例如,在构造函数中放置以下内容:

 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); } } } 

DefaultValueAttribute不会将该属性设置为该值,它纯粹是信息性的。 Visual Studio设计器将此值显示为非粗体,其他值显示为粗体(已更改),但您仍需将属性设置为构造函数中的值。

如果值由用户设置,设计器将为属性生成代码,但您可以通过右键单击属性并单击“ Reset来删除该代码。

编译器不使用DefaultValueAttribute ,并且(可能容易引起混淆)它不会设置初始值。 你需要在构造函数中自己做这个。 使用DefaultValueAttribute地方包括:

  • PropertyDescriptor – 提供ShouldSerializeValue (由PropertyGrid等使用)
  • XmlSerializer / DataContractSerializer / etc(序列化框架) – 用于决定是否需要包含它

相反,添加一个构造函数:

 public MyType() { MyColor = Color.Red; } 

(如果它是带有自定义构造函数的结构,则需要先调用:base()

“DefaultValue”属性不会为您编写代码…而是用于告诉人们(例如Mr Property Grid或Mr Serializer Guy) 打算将默认值设置为Red。

这对于像PropertyGrid这样的东西很有用……因为它会烧掉除红色以外的任何颜色……对于序列化,人们可能会选择省略发送该值,因为你告诉他们这是默认值:)

你在构造函数中初始化MyColor

DefaultValue属性实际上不设置任何值。 它只是指示设计者不生成代码的值,并且还会显示非粗体的默认值以反映这一点。

我改编了Yossarian的答案:

 foreach (PropertyInfo f in this.GetType().GetProperties()) { foreach (Attribute attr in f.GetCustomAttributes(true)) { if (attr is DefaultValueAttribute) { DefaultValueAttribute dv = (DefaultValueAttribute)attr; f.SetValue(this, dv.Value, null); } } }