首页 > 解决方案 > 创建对象时堆栈溢出错误

问题描述

我有一个控制台应用程序,在启动应用程序时出现 Stack Overflow 错误。

主程序

class Program
{
    public static void Main(string[] args)
    {
        Town town = new Town();

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

我的问题是我想用所有建筑物名称的列表来命名 foreach 循环中的所有建筑物,但我想它不起作用,因为它导致了 Stackoverflow,我不知道为什么。有没有更好的方法来做到这一点,或者我在其他地方做错了什么?

public class Town
{
    public Town town = new Town();
    public List<Buildings> buildings = new List<Buildings>();

    private List<string> buildingNames = new List<string>() {"Town_Hall", "Market", "Residences", "Mortician", "Bank", "Hotel", "Tailor", "Gunsmith", "General_Store", "Sheriff", "Well", "Gate", "Wall"};

    public void ResetTown()
    {
        foreach (Buildings building in town)
        {
            int i = 0;
            i++;
            building.Name = buildingNames[i].ToString();
            building.Level = 0;
        }
    }

    public IEnumerator<Buildings> GetEnumerator() 
    { 
        return buildings.GetEnumerator(); 
    } 
}


public class Buildings
{
    public string Name {get; set;}
    public int Level {get; set;}
}

标签: c#foreach

解决方案


查看 Town 的构造函数,你会看到它创建了一个 Town 实例,该实例又调用了自己,从而进入了一个死循环。

换句话说,每个 Town 实例都包含一个 Town 变量,而该变量又包含一个 Town 变量,构造单个 Town 实例需要十亿年和十亿千兆字节。

public Town town = new Town(); 

本质上是一样的

Public Town town;
Public Town()
{
    town = new Town(); //constructor calls itself
 }

推荐阅读