无论如何都隐含地执行以下模式?
[DefaultValue(true)]
public bool SomeBooleanProperty { get; set; } = true;
在两个地方重复默认值似乎只是在某处乞求错误,而且无论如何似乎都是多余的。我可以想象一些将DefaultValueAttribute自动设置为默认值(或任何值)的情况是不可取的,但我认为这些将是例外而不是规则。在这些情况下,解决方案只是在构造函数中设置默认值,而不是在我认为比冗余代码更轻松的声明中。
答案 0 :(得分:5)
MSDN对此DefaultValueAttribute
说DefaultValueAttribute不会自动导致成员 使用属性值初始化。您必须设置初始值 在你的代码中。
This文章建议做这样的事情以避免重复的代码
static public void ApplyDefaultValues(object self)
{
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self)) {
DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
if (attr == null) continue;
prop.SetValue(self, attr.Value);
}
}