.Net DefaultValueAttribute on Properties

前端 未结 6 1239
再見小時候
再見小時候 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:57

    It is informal, but you can use it via reflection, for example, place in your constructor the following:

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

提交回复
热议问题