为什么我不能在构造函数中给lambda-syntax的只读属性赋值?

16

我的案例:

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; } = string.Empty;来初始化只读自动实现属性。 - Lucas Trzesniewski
最后,我写了一篇文章:http://blog.rogatnev.net/2017/09/13/Varieties-of-properties.html - Backs
1个回答

16
public string _prop => string.Empty;

等于:

public string _prop { get { return string.Empty; } }
所以,string.Empty 就像在 get 方法中的方法代码。
public string _prop { get; }

等于:

private readonly string get_prop;
public string _prop { get { return get_prop;} }

所以,你可以在构造函数中给get_prop赋值;

更多信息请参见文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接