C#6.0中的只读属性 [英] Read-Only Property in C# 6.0
问题描述
Microsoft在C#6中引入了一种新语法,可让您将属性设置为只读,如下所示:
Microsoft introduce a new syntax in C#6 that let you set your property to read-only as below:
public class Animal
{
public string MostDangerous { get; } = "Mosquito";
}
我想知道这种方法的附加价值是什么.
I am wondering what is the added value of such approach.
仅写有什么区别?
public class Animal
{
public const string MostDangerous = "Mosquito";
}
甚至:
public class Animal
{
public string MostDangerous
{
get
{
return "Mosquito";
}
}
}
推荐答案
您的示例使用的字符串常量无法显示所有可能性.看一下这段代码:
Your example is using string constants which can't show all the possibilities. Look at this snippet:
class Foo
{
public DateTime Created { get; } = DateTime.Now; // construction timestamp
public int X { get; }
public Foo(int n)
{
X = n; // writeable in constructor only
}
}
只读属性是按实例的,可以从构造函数中进行设置.与 const
字段非常不同,该字段的值必须在编译时确定.属性初始化器是一个单独的功能,它遵循字段初始化器的规则和限制.
Read only properties are per-instance and can be set from the constructor. Very different from a const
field whose value must be determined at compile time. The property initializer is a separate feature and follows the rules and limitations of field initializers.
这篇关于C#6.0中的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!