列表中的StackoverflowException

use*_*148 1 c# stack-overflow class list infinite-loop

这段代码有什么问题?我一直在StackOverlflowException......

public class Places
{
    public string Title { get; set; }
    public string Content { get; set; }
    public double Latitude { get; set; }
    public double Longtitude { get; set; }    


    public List<Places> allPlaces = new List<Places>
    {
        new Places { Title = "test", Content = "test\ntest", Latitude = 52.23057, Longtitude = 5.84582 },
        new Places { Title = "testt", Content = "dfsdf", Longtitude = 52.35589, Latitude = 4.92119 }
    };
}
Run Code Online (Sandbox Code Playgroud)

All*_*nek 5

由于allPlaces是实例字段,因此在构造Places对象期间对其进行初始化.所以你创建了一个Places对象,它创建了一个对象,它在它的集合初始化器中List<Places>创建了另一个Places对象,它创建了另一个List<Places>自己的...一个永无止境的递归.

您可能想要创建一个静态allPlaces字段,该字段只能创建一个列表.将static关键字添加到字段中,如下所示:

public static List<Places> allPlaces = ...
Run Code Online (Sandbox Code Playgroud)