这些是一样的吗?
public string MyProp { get; }
对比
public string MyProp { get; private set; }
我的意思是在两个版本中,属性都可以在它自己的类中设置,但对其他类是只读的?
最佳答案
public string MyProp { get; }
- 这是在 中介绍的C# 6.0。 此类属性称为只读自动属性。对此类成员的赋值只能作为声明的一部分或在同一类的构造函数中发生。您可以在 that MSDN article 中阅读有关它的详细说明或在 Jon Skeet blog.如那篇文章所述,此类属性自动解决了四个问题:
- A read-only-defined backing field
- Initialization of the backing field from within the constructor
- Explicit implementation of the property (rather than using an auto-property)
- An explicit getter implementation that returns the backing field
public string MyProp { get; private set; }
- 这意味着该属性在 中是只读的本类(class)以外 ,但您可以在此类中更改它的值。顺便说一句,您可以使用 C# 6.0 中再次引入的新自动初始化语法设置只读自动属性值:
public string MyProp { get; } = "You cannot change me";
它与以前版本的 C# 的代码相同:private readonly string myProp = "You cannot change me"
public string MyProp { get { return myProp ; } }
或者,在 C# 6.0 中:public string MyProp { get; }
protected MyClass(string myProp, ...)
{
this.MyProp = myProp;
...
}
在以前的版本中等于:private readonly string myProp;
public string MyProp { get { return myProp; } }
protected MyClass(string myProp, ...)
{
this.myProp = myProp;
...
}
关于c# - 仅带有 getter 的属性与带有 getter 和私有(private) setter 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35035632/