【发布时间】:2011-12-04 02:53:00
【问题描述】:
当您有一个在对象实例化时已知且之后不应更改的变量时,应使用只读字段。
但是,不允许从子类的构造函数中分配只读字段。 如果超类是抽象的,这甚至不起作用。
有没有人能很好地解释为什么这不是一个好主意,或者缺乏 C# 语言?
abstract class Super
{
protected readonly int Field;
}
class Sub : Super
{
public Sub()
{
this.Field = 5; //Not compileable
}
}
PS:您当然可以通过在超类的受保护构造函数中分配只读字段来达到相同的结果。
【问题讨论】:
-
编译器错误也不准确:
Error 68 A readonly field cannot be assigned to (except in a constructor or a variable initializer)
标签: c# inheritance variable-assignment readonly restriction