简体   繁体   English

子类构造函数无法在内部分配给readonly变量

[英]child class constructor cannot assign to readonly variable inside

I have this parent class: 我有这个家长班:

public class ParentSchedule
{
    protected readonly int[] numbersArray;
    public ParentSchedule()
    {
        numbersArray = new int[48];
        //code
    }
}

Then I have this child class: 然后我有这个孩子班:

public class ChildSchedule: ParentSchedule
{
    public ChildSchedule()
    {
        numbersArray = new int[24]; //compile time error here
        //code
     }
}

However, at in the child class, I have this error: 但是,在子类中,我遇到此错误:

A readonly field cannot be assigned to (except in a constructor or a variable initializer) 无法将只读字段分配给它(在构造函数或变量初始化程序中除外)

I tried adding the keyword base : 我尝试添加关键字base

public ChildSchedule() : base()

But I still got the same error. 但是我仍然遇到同样的错误。 Is there a way for me to write to the readonly field from the child class? 有没有办法让我从子类写入readonly字段?

Is there a way for me to write to the readonly field from the child class? 有没有办法让我从子类写入只读字段?

No. A readonly field can only be assigned in the constructor of the type that declares it . 不可以。 readonly字段只能在声明它的类型的构造函数中分配。

Perhaps you should make a protected constructor in the base class which contains the value to assign to the variable: 也许您应该在基类中创建一个受保护的构造函数,该构造函数包含要分配给变量的值:

public class ParentSchedule
{
    protected readonly int[] numbersArray;

    protected ParentSchedule(int[] numbersArray)
   {
        this.numbersArray = numbersArray;
    }
}

Then the child class can chain to that constructor: 然后,子类可以链接到该构造函数:

public class ChildSchedule: ParentSchedule
{
    public ChildSchedule() : base(new int[24])
    {
    }
}

Note that the problem isn't accessing the variable (as per your title) - it's assigning to the variable. 请注意,问题不在于访问变量(按照您的标题),而是分配给变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM