对象属性赋初始值写法

1、原始写法,也是最麻烦的一种写法:
private string _text = null;
public string text
{
get
{
return _text;
}
set
{
_text = (_text == null ? "文本" : value);
}
}
接下来所说的所有写法,都算是语法糖,经过反编译之后,还是写成第一种写法。

2、属性允许赋初始值(C#6.0新特性)
public string text
{
get;
set;
} = "文本";
3、使用Lambda表达式
private string _text = null;
public string text
{
get => _text;
set
{
_text = (_text == null ? "文本" : value);
}
}
4、DefaultValueAttribute不会造成一名成员与属性的值被自动初始化,必须在代码中设置初始值。
[DefaultValue(false)]
public bool MyProperty {get;set;}