我在用户控件中获得了以下代码:
[DefaultValue(typeof(Color), "Red")]
public Color MyColor { get; set; }
如何将
MyColor
更改为其默认值? 最佳答案
它是非正式的,但是您可以通过反射来使用它,例如,在构造函数中放置以下内容:
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);
}
}
}
关于c# - .Net DefaultValueAttribute在属性上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/705553/