C#6.0中的只读属性

ehh*_*ehh 10 c# properties c#-6.0

Microsoft在C#6中引入了一种新语法,允许您将属性设置为只读,如下所示:

public class Animal
{
    public string MostDangerous { get; } = "Mosquito";
}
Run Code Online (Sandbox Code Playgroud)

我想知道这种方法的附加价值是什么.

写作有什么区别:

public class Animal
{
    public const string MostDangerous = "Mosquito";
}
Run Code Online (Sandbox Code Playgroud)

甚至:

public class Animal
{
    public string MostDangerous 
    { 
        get
        {
            return "Mosquito";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 20

您的示例使用的字符串常量无法显示所有可能性.看看这个片段:

class Foo
{
    public DateTime Created { get; } = DateTime.Now;  // construction timestamp

    public int X { get; } 

    public Foo(int n)
    {
        X = n;  // writeable in constructor only
    }
}
Run Code Online (Sandbox Code Playgroud)

只读属性是每个实例,可以从构造函数设置.与const必须在编译时确定其值的字段非常不同.属性初始值设定项是一个单独的功能,并遵循字段初始值设定项的规则和限制.