c# - 自动实现的属性是否有隐含的集合?

标签 c#

<分区>

我原以为对 this.GetProp 的赋值会在编译时失败,因为该属性不支持 set。这段代码用 VS2015 和 NET461 编译得很好。

public class Example
{
    public Example(string val)
    {
        this.GetProp = val;
        this.GetSetProp = val;
    }

    public string GetProp { get; }
    public string GetSetProp { get; set; }
}

是否有对自动属性中支持字段的隐含私有(private)访问?

最佳答案

这是 C# 6.0 中新引入的功能。请参阅C# 6.0 语言规范10.7.3 自动实现的属性部分:

If the auto-property has no set accessor, the backing field is considered readonly (§10.5.2). Just like a readonly field, a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.

(强调我的)

关于c# - 自动实现的属性是否有隐含的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45590233/

相关文章:

c# - 如何在 C# 中访问 WinRM

c# - LINQ 将行分组为列

C# 指针 - 静态调用

c# - 查找 Selenium C# 的 CSS 选择器路径

c# - 如何发布对象列表?

c# - 从 .NET(特别是 Windows Phone 7)调用任意 JSON 服务器的最佳方法是什么

c# - WebAPI 路由中的通配符参数不应该匹配

c# - 为什么 Nullable<T> 可以为空?为什么不能重现?

c# - LINQ 中 SQL ISNULL 的等价物?

c# - 如何改进我的第一个 OSS 项目