为什么我不能在构造函数中分配一个lambda语法只读属性?

Tân*_*Tân 15 c#

我的情况:

public class A
{
    public string _prop { get; }
    public A(string prop)
    {
        _prop = prop; // allowed
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个案例:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

两种语法:

public string _prop { get; }
Run Code Online (Sandbox Code Playgroud)

 public string _prop => string.Empty;
Run Code Online (Sandbox Code Playgroud)

创建一个只读属性.但是为什么我不能在第二种情况下分配呢?

Bac*_*cks 16

public string _prop => string.Empty;
Run Code Online (Sandbox Code Playgroud)

等于:

public string _prop { get { return string.Empty; } }
Run Code Online (Sandbox Code Playgroud)

所以,string.Empty就像方法中的方法代码一样get.

public string _prop { get; }
Run Code Online (Sandbox Code Playgroud)

等于:

private readonly string get_prop;
public string _prop { get { return get_prop;} }
Run Code Online (Sandbox Code Playgroud)

所以,你可以get_prop从构造函数中分配一个值;

文章中的更多信息.