我只是在 C# 中尝试一些东西,我遇到了这个,我在类本身中为同一个类创建了一个对象
class Class1
{
public int test1 { get; set; }
Class1 x = new Class1();
}
然后我尝试从另一个抛出错误的类创建对象
An unhandled exception of type 'System.StackOverflowException' occurred in Test.exe
class Program
{
static void Main(string[] args)
{
Class1 x = new Class1();
}
}
我已经用谷歌搜索了,但我没有找到任何与 c# 相关的链接,但我在 c++ 中找到了它,他们说 Class1 是一个不完整的类型,因为它还没有被定义,而是正在被定义。我想知道它是否也适用于 c#
最佳答案
Class1
创建一个 Class1
,它创建另一个 Class1
,它创建另一个 Class1
,它......
因此每个构造函数调用都会被添加到执行堆栈中,直到它溢出。
由于您没有指定要对实例做什么,因此无法知道正确答案是什么。
对于极客幽默,Google recursion
关于C# 在类本身中为同一个类创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30127116/