gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:04:43 25 4
gpt4 key购买 nike

我有课

 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com