DefaultValue attribute is not working with my Auto Property

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!?


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


[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, ie not using an automatically implemented-property:

private bool retrieveAllInfo = true;
[DefaultValue(true)]
public bool RetrieveAllInfo {
    get {return retrieveAllInfo; }
    set {retrieveAllInfo = value; }
}

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);
        }
   }
链接地址: http://www.djcxy.com/p/51340.html

上一篇: 有琐碎的财产曾经拯救了你的培根?

下一篇: DefaultValue属性不适用于我的自动属性