2009-12-30 40 views
19

我有以下的自动属性默认值属性不符合我的自动属性工作

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

,当我尝试使用它的代码我发现默认为false是false里面我认为这是默认值一个bool变量,有没有人有线索有什么不对?!

+0

[Similar questions](http://stackoverflow.com/questions/705553/net-defaultvalueattribute-on-properties)。在VS2015中:'public bool RetrieveAllInfo {get;组; } = true;'这是[C#6](https://blogs.msdn.microsoft.com/csharpfaq/2014/11/20/new-features-in-c-6/)功能。 – marbel82 2016-11-08 13:17:06

回答

26

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

更多资讯:http://support.microsoft.com/kb/311339

+1

谢谢Philippe,所以我认为唯一的解决方案是来自构造函数。谢谢 – 2009-12-31 06:39:21

11

[DefaultValue]仅由(例如)序列化的API(如XmlSerializer),和一些用户界面元素(如PropertyGrid)。它没有设置值本身;你必须使用一个构造函数为:

public MyType() 
{ 
    RetrieveAllInfo = true; 
} 

或手动设置字段,即不使用自动实现的属性:

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

一劈为这是对this链接。

总之,在构造函数的末尾调用这个函数。

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

这是危险的,不应该使用。在派生类有机会设置使属性设置器工作所需的任何内容之前,这会在基类构造函数完成之前设置派生类的属性。 – hvd 2013-06-21 10:41:14