.NET默认值属性默认值、属性、NET

2023-09-07 01:48:00 作者:你还是我年少时的梦

我听到人们说关于默认值属性包括一些不同的东西:

I've heard people say a few different things about the DefaultValue attribute including:

它集之前什么都使用它的属性的值。 它不适合autoproperties工作。 这只是用来装饰的,你必须手动设置实际的默认值。 "It sets the value of the property before anything else uses it." "It doesn't work for autoproperties." "It's only for decoration. You must manually set actual default values."

哪个(如果有的话)是正确的?请问默认值实际设置的默认值?有没有情况下,它不工作?难道只是最好不要用它?

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?

推荐答案

在这里我通常使用的地方默认值是反序列化的XML类这是串行/。它的不实例化过程中设置的默认值,不会影响autoproperties。

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不会导致成员被自动与属性的值初始化。您必须设置的初始值在code。

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类

编辑:罗兰指出,随着人在他们的答案中提到的属性也使用窗体设计器

As Roland points out, and as others mentioned in their answers the attribute is also used by the Form Designer

 
精彩推荐
图片推荐