.NET 默认值属性 [英] .NET DefaultValue attribute

查看:37
本文介绍了.NET 默认值属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说人们对 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 类

正如罗兰指出的那样,正如其他人在他们的回答中提到的,表单设计器也使用了该属性

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

这篇关于.NET 默认值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆