"DefaultValue" 属性在我的自动属性中不起作用。

24
我有以下自动属性。
[DefaultValue(true)]
public bool RetrieveAllInfo { get; set; }

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


1
类似问题:链接。在VS2015中:public bool RetrieveAllInfo { get; set; } = true; 这是C# 6的新特性。 - marbel82
3个回答

43

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

更多信息请参见:http://support.microsoft.com/kb/311339


2
谢谢Philippe,所以我认为唯一的解决方案是从构造函数开始。谢谢。 - Ahmed Magdy

18

[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)]
public bool RetrieveAllInfo { get; set; } = true;

大家好,这是一个老问题。现在仅使用自动实现属性生成代码是否安全?并且删除RetreiveAllInfo字段?我的意思是直接使用public bool RetreiveAllInfo {get;set;} = true吗?为什么我还能看到大多数UI库使用旧的方式呢? - KOGRA
1
@KOGRA "没问题,可以的" 和 "因为就像这个答案所说:当时这种语法还不存在"(这是C# 6中的“自动属性初始化器”功能) - Marc Gravell

0

解决这个问题的一个方法是在这个链接上。

简而言之,在构造函数结束时调用此函数。

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

5
这很危险,不应该使用。这会在基类构造函数完成之前设置派生类的属性,在派生类有机会设置所有需要使属性设置器正常工作的内容之前进行操作。 - user743382

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接