【发布时间】: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