你如何给一个C#自动属性的默认值? [英] How do you give a C# Auto-Property a default value?
本文介绍了你如何给一个C#自动属性的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何给一个C#自动属性的默认值?我要么使用构造,或恢复到旧的语法。
How do you give a C# Auto-Property a default value? I either use the constructor, or revert to the old syntax.
使用构造:
class Person
{
public Person()
{
Name = "Default Name";
}
public string Name { get; set; }
}
使用正常的属性语法(带有默认值)
private string name = "Default Name";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
有没有更好的办法?
Is there a better way?
推荐答案
在C#5和更早版本,给自动实现的属性的默认值,你必须做在构造函数中。
In C# 5 and earlier, to give auto implemented properties a default value, you have to do it in a constructor.
要具备自动初始化属性的能力,因为C#6.0包括在内。语法是:
The ability to have auto property initializers is included since C# 6.0. The syntax is:
public int X { get; set; } = x; // C# 6 or higher
这篇关于你如何给一个C#自动属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文