C# - 只读属性和字段不能在派生类构造函数中设置

标签 c# constructor derived-class readonly-attribute

<分区>

我有一个像下面这样的类结构

abstract class AMyAbstractClass {
    public readonly int MyReadonlyField;
    public int MyReadonlyProperty { get; }//read-only auto-property (syntactic sugar)
}
class MyConcreteClass : AMyAbstractClass {
    MyConcreteClass() {
        this.MyReadonlyField = 1;
        this.MyReadonlyProperty = 1;
    }
}

这会引发编译错误

A readonly field cannot be assigned to (except in a constructor or a variable initializer)

Property or indexer 'AMyAbstractClass.MyReadonlyProperty cannot be assigned to -- it is read only

分别。

在第一种情况下,错误消息是错误的,因为它是在构造函数中设置的!


我可以想出其他方法来拥有不可变的对象属性,但为什么这种情况是不允许的?这种类型的封装有哪些好的做法?

最佳答案

您需要通过基类的构造函数传播它们:

abstract class AMyAbstractClass {
    public readonly int MyReadonlyField;
    public int MyReadonlyProperty { get; }//syntactic sugar
    protected AMyAbstractClass (int fieldValue, int propertyValue) {
        this.MyReadonlyField = fieldValue;
        this.MyReadonlyProperty = propertyValue;
    }
}
class MyConcreteClass : AMyAbstractClass {
    public MyConcreteClass() 
        : base(fieldValue: 1, propertyValue:1) {
    }
}

关于 readonly 字段。引用自ECMA-334 C# Language Specification, chapter 15.5.3 :

When a field - declaration includes a readonly modifier, the fields introduced by the declaration are readonly fields . Direct assignments to readonly fields ca n only occur as part of that declaration or in an instance constructor or static constructor in the same class.

以及 read-only auto-properties 的描述来自 C# 6:

... properties can be set only in the body of a constructor:

关于C# - 只读属性和字段不能在派生类构造函数中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57362098/

相关文章:

c++ - 模板部分特化防止从派生类初始化

c# - 如何在 C# Xamarin Android 中实现媒体播放器监听器?

c# - 订购字典

c++ - 这些构造函数有什么区别?

constructor - F# 中的静态构造函数 - 它们何时运行?

C++ 和 OpenMP : How to make the initializer list of a constructor critical?

c# - 如何在 C# 中添加启动画面?

c# - .NET Xml 序列化 : Integer Element with Attribute?

c# - 如何将使用 Activator.CreateInstance 创建的对象句柄解包到基类?

java - Spark : . saveAsTextFile 丢失 Java 对象的继承字段