净DefaultValueAttribute上的属性 [英] .Net DefaultValueAttribute on Properties

查看:188
本文介绍了净DefaultValueAttribute上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这个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);
        }
    }
}

这篇关于净DefaultValueAttribute上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆