C# 为什么可以';是否在构造函数中为lambda语法只读属性赋值?
我的情况是:C# 为什么可以';是否在构造函数中为lambda语法只读属性赋值?,c#,C#,我的情况是: public class A { public string _prop { get; } public A(string prop) { _prop = prop; // allowed } } 另一种情况: public class A { public string _prop => string.Empty; public A(string prop) { // Property
public class A
{
public string _prop { get; }
public A(string prop)
{
_prop = prop; // allowed
}
}
另一种情况:
public class A
{
public string _prop => string.Empty;
public A(string prop)
{
// Property or indexer 'A._prop' cannot be assigned to -- it is read only
_prop = prop;
}
}
两种语法:
public string _prop { get; }
及
创建只读属性。但是为什么我不能在第二种情况下分配它呢
public string _prop => string.Empty;
等于:
public string _prop { get { return string.Empty; } }
private readonly string get_prop;
public string _prop { get { return get_prop;} }
因此,string.Empty
类似于方法get
中的方法代码
public string _prop { get; }
等于:
public string _prop { get { return string.Empty; } }
private readonly string get_prop;
public string _prop { get { return get_prop;} }
因此,您可以从构造函数中分配get_prop
一个值
更多信息参见。还有
公共字符串Prop{get;}=string.Empty
初始化只读自动实现的属性。最后,我写了一篇文章: