gpt4 book ai didi

c# - 类本身内部的类实例

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:49 25 4
gpt4 key购买 nike

此代码有效:

class Person{
public Person p;
public string name;
private int age;

}
class Solution {


static void Main(String[] args) {

Person z = new Person () { name = "Stacl"};
Console.WriteLine (z.name);
Person a = new Person ();
Console.WriteLine (a.name);

}
}

但这行不通:

class Person{
public Person p = new Person (){name = "Inside",age = 45}; // add 'new'
public string name;
private int age;

}
class Solution {


static void Main(String[] args) {

Person z = new Person () { name = "Stacl"};
Console.WriteLine (z.name);
Person a = new Person ();
Console.WriteLine (a.name);

}
}

你能给我解释一下这是怎么发生的以及为什么会发生吗?

最佳答案

正如@Lucas 在评论中提到的,这会导致创建Person 的无限循环。

如果不初始化p 字段,就不能构造Person,它构造一个Person,它构造一个Person等...

当然,这最终会导致 StackOverflowException

关于c# - 类本身内部的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27837924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com