.NET DefaultValue attribute(.NET DefaultValue 属性)
问题描述
我听说人们对 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 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.NET DefaultValue 属性
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
