我有一个像下面这样的类结构
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: