[英]Why can't I assign to an lambda-syntax read-only property in the constructor?
My case: 我的情况:
public class A
{
public string _prop { get; }
public A(string prop)
{
_prop = prop; // allowed
}
}
Another case: 另一个案例:
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;
}
}
Both syntax: 两种语法:
public string _prop { get; }
and 和
public string _prop => string.Empty;
create a read only property. 创建一个只读属性。 But why coundn't I assign it in the second case?
但是为什么我不能在第二种情况下分配呢?
public string _prop => string.Empty;
is equal to: 等于:
public string _prop { get { return string.Empty; } }
So, string.Empty
is like method code in method get
. 所以,
string.Empty
就像方法get
方法代码一样。
public string _prop { get; }
is equal to: 等于:
private readonly string get_prop;
public string _prop { get { return get_prop;} }
So, you can assign get_prop
a value from constructor; 因此,您可以从构造函数中为
get_prop
指定一个值;
More information in the article . 文章中的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.