【发布时间】:2020-02-24 05:18:20
【问题描述】:
一个类,它本身包含它自己的实例化对象,当在 c# 的 main 方法中创建该类的对象时,它会给出 stackoverflowExeption。为什么??我想要它的原因,而不是解决方案。谢谢
namespace project_1
{
class check
{
check checkobject = new check();// Line-1
/*I have not access Line-1 in main method.
But due to Line-1 or Line-2, output says "Process is terminating due to StackOverflowException". Why??
I do not need the solution, I want to know the reason for it.
Removing " new check() " from Line-1, then it works fine.
*/
public void Display() {
Console.WriteLine("It worked");
}
}
class DemoProgram
{
static void Main(string[] args)
{
check ob1 = new check();// Line-2
ob1.Display();
}
}
}
【问题讨论】:
-
您正在递归地实例化该类,因此您的堆栈内存不足。看看这个答案:stackoverflow.com/a/34182621/10531996
-
问题在于它正在无限地创建越来越多的实例
标签: c# stack-overflow