.Net DefaultValueAttribute on Properties

前端 未结 6 1242
再見小時候
再見小時候 2020-12-01 21:28

I got this code in a user control:

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

How can I change MyColor

6条回答
  •  佛祖请我去吃肉
    2020-12-01 21:44

    DefaultValueAttribute is not used by the compiler, and (perhaps confusingly) it doesn't set the initial value. You need to do this your self in the constructor. Places that do use DefaultValueAttribute include:

    • PropertyDescriptor - provides ShouldSerializeValue (used by PropertyGrid etc)
    • XmlSerializer / DataContractSerializer / etc (serialization frameworks) - for deciding whether it needs to be included

    Instead, add a constructor:

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

    (if it is a struct with a custom constructor, you need to call :base() first)

提交回复
热议问题