问题描述
我听说人们对 DefaultValue
属性有一些不同的看法,包括:
I've heard people say a few different things about the DefaultValue
attribute including:
- 它在其他任何东西使用它之前设置属性的值."
- 它不适用于自动属性."
- 只是为了装饰,你必须手动设置实际的默认值."
哪个(如果有)是正确的?DefaultValue
是否真的设置了默认值?有没有不起作用的情况?最好不要使用它吗?
Which (if any) is right? Does DefaultValue
actually set default values? Are there cases where it doesn't work? Is it best just not to use it?
推荐答案
我通常使用 DefaultValue
的地方是用于序列化/反序列化为 XML 的类.它不在实例化期间设置默认值,并且不影响自动属性.
The place where I typically used DefaultValue
is for classes which are serialized/deserialized to XML. It does not set the default value during instantiation and doesn't impact autoproperties.
来自 MSDN:
DefaultValueAttribute 不会导致成员使用属性值自动初始化.您必须在代码中设置初始值.
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
MSDN - DefaultValueAttribute 类
正如 Roland 所指出的,正如其他人在回答中提到的那样,表单设计器也使用了该属性
As Roland points out, and as others mentioned in their answers the attribute is also used by the Form Designer
这篇关于.NET DefaultValue 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!