c# - 在没有 setter 的情况下设置属性。这怎么不是编译错误?

标签 c# .net

我有课

 public class Settings : ProviderSettings {
        internal Settings(MyProvider provider) {
            this.Provider = provider;
            LoadFromConfig();
        }

        protected override IProvider Provider {
            get;
        }
}

ProviderSettings 类是:

 public abstract class ProviderSettings {
          protected abstract IProvider Provider { get; }
 }

在 Visual Studio 2015 中,当我以 .NET 4.0 为目标时,我没有收到编译错误。我想我应该收到一个编译错误,说“Provider 是只读的,无法设置”。为什么编译器允许这样做?

最佳答案

如果您不指定 setter,则 getter-only 自动属性的支持字段将隐式声明为 readonly。您可以从构造函数或使用属性初始化程序对其进行初始化。这是 C# 6 的新特性。

所以实际上你的代码将被编译为

public abstract class ProviderSettings
{
    protected abstract IProvider get_Provider();
    // there is no property setter
}

public class Settings : ProviderSettings
{
    private readonly IProvider _provider;

    internal Settings(MyProvider provider) {
        _provider = provider; // assignment directly to backing field
        LoadFromConfig();
    }

    protected override IProvider get_Provider()
    {
        return _provider;
    }
    // there is no property setter
}

C# 6 Language Specification的相关部分(草稿):

If the auto-property has no set accessor, the backing field is considered readonly. 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# - 在没有 setter 的情况下设置属性。这怎么不是编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41990987/

相关文章:

c# - 为什么 Visual C# 2008 Express 中缺少 StringBuilder 类的 Chars 属性?

c# - 模拟对具有 List 类型属性的对象的调用

c# - 计算两个数: what's the meaning of optimizations?的算术平均值(average)

C# Discord.net 添加文件作为图像嵌入

c# - 使用元组 c# 一次将所有项目从类返回到表单

c# - Apache Active MQ .Net 客户端 (Apache NMS) 和 Visual Studio 2010 C# Express

c# - 在 .NET 中获取 DLL 的详细信息

.net - 未处理通过 MSMQ 的较大 WCF 消息

.net - 为什么 .Net 引用类型中有接口(interface)?

c# - Automapper:从自动映射对象解析源属性名称