如何给C#自动属性一个初始值?
我要么使用构造函数,要么恢复到旧语法。
使用构造函数:
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#9.0中添加了对init关键字的支持,这是一种非常有用且非常复杂的声明只读自动属性的方法:
声明:
class Person
{
public string Name { get; init; } = "Anonymous user";
}
~享受~使用:
// 1. Person with default name
var anonymous = new Person();
Console.WriteLine($"Hello, {anonymous.Name}!");
// > Hello, Anonymous user!
// 2. Person with assigned value
var me = new Person { Name = "@codez0mb1e"};
Console.WriteLine($"Hello, {me.Name}!");
// > Hello, @codez0mb1e!
// 3. Attempt to re-assignment Name
me.Name = "My fake";
// > Compilation error: Init-only property can only be assigned in an object initializer
在C#(6.0)及更高版本中,您可以执行以下操作:
对于只读财产
public int ReadOnlyProp => 2;
对于可写和可读财产
public string PropTest { get; set; } = "test";
在当前版本的C#(7.0)中,您可以执行以下操作:(代码段显示了如何使用表达式体的get/set访问器,使其在与后台字段一起使用时更加紧凑)
private string label = "Default Value";
// Expression-bodied get / set accessors.
public string Label
{
get => label;
set => this.label = value;
}
在C#9.0中添加了对init关键字的支持,这是一种非常有用且非常复杂的声明只读自动属性的方法:
声明:
class Person
{
public string Name { get; init; } = "Anonymous user";
}
~享受~使用:
// 1. Person with default name
var anonymous = new Person();
Console.WriteLine($"Hello, {anonymous.Name}!");
// > Hello, Anonymous user!
// 2. Person with assigned value
var me = new Person { Name = "@codez0mb1e"};
Console.WriteLine($"Hello, {me.Name}!");
// > Hello, @codez0mb1e!
// 3. Attempt to re-assignment Name
me.Name = "My fake";
// > Compilation error: Init-only property can only be assigned in an object initializer
除了已经接受的答案外,对于要将默认属性定义为其他财产的函数的场景,您可以在C#6.0(及更高版本)上使用表达式体表示法来实现更优雅、更简洁的结构,如:
public class Person{
public string FullName => $"{First} {Last}"; // expression body notation
public string First { get; set; } = "First";
public string Last { get; set; } = "Last";
}
您可以按以下方式使用以上内容
var p = new Person();
p.FullName; // First Last
p.First = "Jon";
p.Last = "Snow";
p.FullName; // Jon Snow
为了能够使用上述“=>”表示法,属性必须是只读的,并且不使用get accessor关键字。
MSDN上的详细信息