c# - 创建对象时堆栈溢出错误
问题描述
我有一个控制台应用程序,在启动应用程序时出现 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;}
}
解决方案
查看 Town 的构造函数,你会看到它创建了一个 Town 实例,该实例又调用了自己,从而进入了一个死循环。
换句话说,每个 Town 实例都包含一个 Town 变量,而该变量又包含一个 Town 变量,构造单个 Town 实例需要十亿年和十亿千兆字节。
public Town town = new Town();
本质上是一样的
Public Town town;
Public Town()
{
town = new Town(); //constructor calls itself
}
推荐阅读
- java - JAVA:在来自firestore的android中的图像滑块中显示数据
- sql - 如何使用主游标数据打开多个游标
- java - Camunda 与 SpringBoot:JSON 在 64 KB 后被切断
- laravel - 混合清单不存在 laravel vuejs 错误
- java - 编写一个程序,打印 s 中字母按字母顺序出现的最长子串
- c# - mvvm 从加载的视图模型中交叉执行方法
- c - 核心转储分段错误
- javascript - Vue.js - 全局共享状态和组件外的 for 循环 - 这是一个好习惯吗?
- sql - 如何编写查询以删除重复项并根据 SQL 中的频率对表进行排序?
- rust - 无法移出位于可变引用后面的 ***