C# DefaultValue属性不适用于我的自动属性

C# DefaultValue属性不适用于我的自动属性,c#,properties,attributes,default-value,automatic-properties,C#,Properties,Attributes,Default Value,Automatic Properties,我有以下汽车财产 [DefaultValue(true)] public bool RetrieveAllInfo { get; set; } 当我尝试在代码中使用它时,我发现默认的false为false我假设这是bool变量的默认值,有人知道哪里出了问题吗 DefaultValue属性仅用于告诉Visual Studio设计器(例如,在设计表单时)属性的默认值是什么。它不会在代码中设置属性的实际默认值 此处的更多信息:[DefaultValue]仅由(例如)序列化API(如XmlSerial

我有以下汽车财产

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

当我尝试在代码中使用它时,我发现默认的false为
false
我假设这是
bool
变量的默认值,有人知道哪里出了问题吗

DefaultValue属性仅用于告诉Visual Studio设计器(例如,在设计表单时)属性的默认值是什么。它不会在代码中设置属性的实际默认值


此处的更多信息:

[DefaultValue]
仅由(例如)序列化API(如
XmlSerializer
)和一些UI元素(如
PropertyGrid
)使用。它不设置值本身;您必须为此使用构造函数:

public MyType()
{
    RetrieveAllInfo = true;
}
或手动设置字段,即不使用自动实现的属性:

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

或者,对于较新的C#版本(C#6或更高版本):

[DefaultValue(true)]
公共bool RetrieveAllInfo{get;set;}=true;
链接上有一个黑客

简而言之,在构造函数末尾调用此函数

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);
        }
   }

谢谢Philippe,所以我认为唯一的解决方案是从构造器。谢谢这很危险,不应该使用。这将在基类构造函数完成之前,在派生类有机会设置使属性设置器工作所需的任何内容之前,设置派生类的属性。。在VS2015中:
public bool RetrieveAllInfo{get;set;}=true这是功能。你好,这是一个老问题。但现在只使用自动实现属性的代码生成安全吗?并删除retreiveAllInfo字段?我的意思是
public bool RetreiveAllInfo{get;set;}=true
直接?为什么我仍然看到大多数UI库使用旧的方式。@KOGRA“是的,这很好”,以及“因为像这样的答案:它们是在不存在这种语法的情况下编写的”(这是C#6中的“自动属性初始值设定项”功能)