DefaultValue attribute is not working with my Auto Property

六月ゝ 毕业季﹏ 提交于 2019-11-27 02:36:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!