问题描述
如何为 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# 自动属性赋予初始值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!