phi*_*eld 19 c# inheritance readonly restriction variable-assignment
当你有一个在object-instatiation时已知的变量时,应该使用readonly字段,之后不应该更改.
但是,不允许从子类的构造函数中分配只读字段.如果超类是抽象的,这甚至都不起作用.
有没有人有一个很好的解释为什么这不是一个好主意,或缺乏C#languange?
abstract class Super
{
protected readonly int Field;
}
class Sub : Super
{
public Sub()
{
this.Field = 5; //Not compileable
}
}
Run Code Online (Sandbox Code Playgroud)
PS:您当然可以通过在超类中的受保护构造函数中分配只读字段来获得相同的结果.
Ren*_*ama 10
public class Father
{
protected readonly Int32 field;
protected Father (Int32 field)
{
this.field = field;
}
}
public class Son : Father
{
public Son() : base(5)
{
}
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试这样的东西!