【问题标题】:Populate array in constructor在构造函数中填充数组
【发布时间】:2019-05-22 11:30:24
【问题描述】:

我有一个简单的类,它有 3 个公共字段和 1 个数组类型的私有字段。在构造函数中,我想用类本身的对象初始化数组私有字段

我做以下事情

public class Student
{
    public int StudentID { get; set; }
    public String StudentName { get; set; }
    public int Age { get; set; }
    private Student[] _studentArray;
    public Student()
    {
        _studentArray = new Student[]{
        new Student() { StudentID = 1, StudentName = "John", Age = 18 },
        new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 },
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 },
        new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 },
        new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 },
        new Student() { StudentID = 6, StudentName = "Chris",  Age = 17 },
        new Student() { StudentID = 7, StudentName = "Rob",Age = 19  },
    };
}

我构建并运行,我收到以下错误:

System.StackOverflowException: '异常类型 'System.StackOverflowException' 被抛出。'

【问题讨论】:

  • 您的代码中存在无限递归(ctor 调用 ctor,后者调用 ctor 等),这就是您获得 SOE 的原因。也许您想将Students 保留在static 数组中?将其设为实例有什么意义?

标签: c# arrays constructor initialization


【解决方案1】:

这是因为您正在创建该数组的无限实现,因为您正在创建您初始化的类的数组。该构造函数将永远无法完成,因为构造函数中的每个条目都会自行生成 x 次。每一个又重复了 x 次,因此无休止地继续

【讨论】:

    【解决方案2】:

    这是因为无限循环(每个学生对象初始化其他学生的 _studentArray 等等)。 您需要 2 个类:一个包含 studentArray 的 Student 类和仅具有 StudentID、StudentName 和 Age 属性的 Student 类。

    【讨论】:

      【解决方案3】:

      您的代码是递归的,会导致无限循环。发生这种情况是因为

      new Student()
      

      调用Student类的无参数构造函数,然后尝试通过再次调用构造函数来实例化一个新的Student,依此类推。我想你知道我要去哪里了?

      【讨论】:

        【解决方案4】:

        由于您像他们所说的那样进行无休止的递归,因此您可以创建 2 个类。 1 类用于您的学生属性与 ctor 和 1 类用于学生列表,可能如下所示:

        学生班:

        public class Student
        {
            public int studentID { get; set; }
            public String studentName { get; set; }
            public int age { get; set; }
            public Student(int StudentID, string StudentName, int Age)
            {
                 studentID = StudentID;
                 studentName= StudentName;
                 age = Age;
            }
        }
        

        那么第二类是 StudentList,您可以在其中使用 Add 方法添加学生的数据:

        public class StudentList : Collection<Student>
        {
           public Student this[int ctr]
           {
              get{return this.Items[ctr]; }
              set{ this.Items[ctr] = value; }
           }
        
            new public Student Add(Student newStudent)
            {
                this.Items.Add(newStudent);
                return (Student)this.Items[this.Items.Count-1];
            }
        }
        

        您现在可以初始化 StudentList 并使用 add 方法。希望这会有所帮助。

        【讨论】:

        • 谢谢,我会这么做的
        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 1970-01-01
        • 2016-08-02
        • 2021-09-13
        相关资源
        最近更新 更多