What is the best way to give a C# auto-property an initial value?(为 C# 自动属性赋予初始值的最佳方法是什么?)
问题描述
如何为 C# 自动属性赋予初始值?
How do you give a C# auto-property an initial value?
我要么使用构造函数,要么恢复到旧语法.
I either use the constructor, or revert to the old syntax.
使用构造函数:
class Person
{
public Person()
{
Name = "Initial Name";
}
public string Name { get; set; }
}
使用普通属性语法(带有初始值)
private string name = "Initial Name";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
有没有更好的办法?
推荐答案
在 C# 5 及更早版本中,要为自动实现的属性赋予初始值,您必须在构造函数中进行.
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.
从 C# 6.0 开始,您可以在线指定初始值.语法是:
Since C# 6.0, you can specify initial value in-line. The syntax is:
public int X { get; set; } = x; // C# 6 or higher
DefaultValueAttribute
旨在供 VS 设计者(或任何其他消费者)用来指定默认值,而不是初始值.(即使在设计对象中,初始值也是默认值).
DefaultValueAttribute
is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).
在编译时 DefaultValueAttribute
不会影响生成的 IL,也不会读取它来将属性初始化为该值(请参阅 DefaultValue 属性不适用于我的自动属性).
At compile time DefaultValueAttribute
will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).
影响 IL 的属性示例是 ThreadStaticAttribute
,CallerMemberNameAttribute
, ...
Example of attributes that impact the IL are ThreadStaticAttribute
, CallerMemberNameAttribute
, ...
这篇关于为 C# 自动属性赋予初始值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为 C# 自动属性赋予初始值的最佳方法是什么?


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01