类本身内部的实例

时间:2015-01-08 10:29:42

标签: 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);

    }
}

但这不起作用:

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

    }
}

你能告诉我这是怎么回事以及为什么会这样吗?

2 个答案:

答案 0 :(得分:11)

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

如果没有初始化Person字段,构建p,构建Person等等,则无法构建Person

当然,最终会产生StackOverflowException

答案 1 :(得分:0)

你实际想要达到的目的是:

class Person{
    public string name = "Inside";
    private int age  = 45;
}

在Person实例中创建Person实例将导致StackOverflowException。 但是,由于您从外部访问“名称”字段而非“p”字段,因此无论如何都没有必要。

顺便说一下,您应该用属性替换公共字段,因为这是推荐的样式。

class Person{
    public Person() {
        Name = "Inside";
    }

    public string Name {get; set;}
    private int age = 45;
}