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
:
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?
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 .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.