我有课
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/