c# - 仅带有 getter 的属性与带有 getter 和私有(private) setter 的属性

标签 c#

这些是一样的吗?

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/

相关文章:

c# - 带有附加列的sql批量插入

C# LINQ 构建具有匿名类型的表达式

c# - 调用 'ShutdownBlockReasonCreate'函数不能阻止用户关闭系统

c# - 如何使内存中进程具有事务性?

c# - 写一个Rx "RetryAfter"扩展方法

javascript - 如何将 Jquery Datatables Ellipsis 渲染器用于模板字段链接按钮?

C# 6.0 功能不适用于 Visual Studio 2015

c# - 是否有适用于 Windows Core Audio 的 COM 类型库

c# - Math.Atan2 产生奇怪的结果?

c# - 列表框不显示特定对象的值(数据绑定(bind))