问题
I have the following Auto Property
[DefaultValue(true)]
public bool RetrieveAllInfo { get; set; }
when I try to use it inside the code i find the default false for is false
I assume this is the default value to a bool
variable, does anyone have a clue what is wrong!?
回答1:
The DefaultValue attribute is only used to tell the Visual Studio Designers (for example when designing a form) what the default value of a property is. It doesn't set the actual default value of the attribute in code.
More info here: http://support.microsoft.com/kb/311339
回答2:
[DefaultValue]
is only used by (for example) serialization APIs (like XmlSerializer
), and some UI elements (like PropertyGrid
). It doesn't set the value itself; you must use a constructor for that:
public MyType()
{
RetrieveAllInfo = true;
}
or set the field manually, i.e. not using an automatically implemented-property:
private bool retrieveAllInfo = true;
[DefaultValue(true)]
public bool RetrieveAllInfo {
get {return retrieveAllInfo; }
set {retrieveAllInfo = value; }
}
回答3:
One hack for this is on this link.
In short, call this function at the end of constructor.
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);
}
}
来源:https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property