净DefaultValueAttribute上的属性属性、DefaultValueAttribute

2023-09-02 21:30:50 作者:暮光是深岛

我得到这个code用户控件:

I got this code in a user control:

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

如何修改 MyColor 来作为它的默认值?

How can I change MyColor to be its default value?

推荐答案

这是非正式的,但你可以通过反射使用它,例如,发生在你的构造如下:

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