DefaultValue attribute is not working with my Auto Property

后端 未结 3 1572
迷失自我
迷失自我 2020-12-09 16:21

I have the following Auto Property

[DefaultValue(true)]
public bool RetrieveAllInfo { get; set; }

when I try to use it inside the code i f

相关标签:
3条回答
  • 2020-12-09 16:53

    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);
            }
       }
    
    0 讨论(0)
  • 2020-12-09 17:12

    [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; }
    }
    
    0 讨论(0)
  • 2020-12-09 17:14

    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

    0 讨论(0)
提交回复
热议问题