类本身内部的实例

Per*_*kie 1 c# oop instance

此代码有效:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

你能解释一下这是怎么回事以及为什么会这样吗?

Rot*_*tem 11

正如@Lucas在评论中提到的那样,这会导致无限循环的创作Person.

你不能在Person没有初始化p字段的情况下构造一个构造a 的字段,Person构造a Person等...

当然,最终会导致一个StackOverflowException.