一个类本身包含它自己实例化的对象,当在c#的main方法中创建该类的对象时,它会给出stackoverflowExeption。为什么??我想要它的原因,而不是solution.Thanks
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();
}
}
}发布于 2020-02-24 13:20:43
这是因为当您从main方法创建新的check对象时,它会触发实例变量checkobject的初始化,这将再次创建check类的对象。这是一个无限的过程,因此分配给您的程序的内存已耗尽。
发布于 2020-02-24 13:26:06
每次初始化类时,都会调用类的构造函数。标记为行1的行是您不应该拥有的行。这意味着你可以递归地调用你的构造函数。
发布于 2020-02-24 14:10:00
如果您尝试您的程序,您将看到与以下类似的输出。如果您几乎不知道为什么会发生这种情况,那么至少您可以根据构造函数来猜测出了什么问题。
Compilation succeeded - 1 warning(s)
jdoodle.cs(5,11): warning CS0414: The private field `check.checkobject' is assigned
but its value is never used
Stack overflow: IP: 0x5647646e1705, fault addr: 0x7fffc422eff8
Stacktrace:
at <unknown> <0xffffffff>
at (wrapper alloc) object.AllocSmall (intptr,intptr) <0x00103>
<...>
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
........
........
........
........
........
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
output Limit reached.https://stackoverflow.com/questions/60369943
复制相似问题