此代码有效:
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/