Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 子类构造函数无法分配给内部的只读变量_C#_Asp.net - Fatal编程技术网

C# 子类构造函数无法分配给内部的只读变量

C# 子类构造函数无法分配给内部的只读变量,c#,asp.net,C#,Asp.net,我有一个父类: public class ParentSchedule { protected readonly int[] numbersArray; public ParentSchedule() { numbersArray = new int[48]; //code } } 然后我有一个儿童班: public class ChildSchedule: ParentSchedule { public ChildSch

我有一个父类:

public class ParentSchedule
{
    protected readonly int[] numbersArray;
    public ParentSchedule()
    {
        numbersArray = new int[48];
        //code
    }
}
然后我有一个儿童班:

public class ChildSchedule: ParentSchedule
{
    public ChildSchedule()
    {
        numbersArray = new int[24]; //compile time error here
        //code
     }
}
但是,在子类中,我有以下错误:

无法将只读字段分配给(构造函数或变量初始值设定项中除外)

我尝试添加关键字
base

public ChildSchedule() : base()
但我还是犯了同样的错误。有没有办法从子类写入
只读
字段

有没有办法从子类写入只读字段

不可以。只能在声明该字段的类型的构造函数中指定该字段

也许您应该在基类中创建一个受保护的构造函数,其中包含要分配给变量的值:

public class ParentSchedule
{
    protected readonly int[] numbersArray;

    protected ParentSchedule(int[] numbersArray)
   {
        this.numbersArray = numbersArray;
    }
}
然后子类可以链接到该构造函数:

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

请注意,问题不是访问变量(根据您的标题)-而是分配给变量。

只读字段只能在声明它的类型的构造函数中分配。
此描述对我帮助很大。