我有一个控制台应用程序,启动该应用程序时出现堆栈溢出错误。
主程序
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;}
}
答案 0 :(得分:1)
看一下Town的构造函数,您将看到它创建了Town实例,该实例再次调用自身,从而进入一个无限循环。
按顺序来说,每个Town实例都包含Town变量,而Town变量又包含Town变量,要构造一个Town实例将需要十亿年和十亿兆字节。
public Town town = new Town();
与
基本相同Public Town town;
Public Town()
{
town = new Town(); //constructor calls itself
}
答案 1 :(得分:0)
它是递归的,每次创建城镇时,创建城镇都会永远持续下去,宇宙会崩溃成奇点
public class Town
{
public Town town = new Town()
...
您可能想要的是这个
public class Town
{
// when you auto initialise a property,
// it gets created when your create the class
// this is your recursion, lets get rid of it as its completely
// unneeded
//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()
{
// notice now we dont need a reference to town
// we "are" the town
foreach (Buildings building in this)
{
int i = 0;
i++;
building.Name = buildingNames[i].ToString();
building.Level = 0;
}
}
public IEnumerator<Buildings> GetEnumerator()
{
return buildings.GetEnumerator();
}
}
用法相同
public static void Main(string[] args)
{
Town town = new Town();
}
答案 2 :(得分:0)
您也可以使用它。将Building
标记为课程,而不是Buildings
。
将建筑物与城镇分离,并通过构造函数将其注入:
此外,您的int i = 0; i++
有错误,并且可能导致 IndexOutOfRangeException 。
public class Town
{
private List<Building> buildings;
private List<string> buildingNames = new List<string>() {"Town_Hall", "Market", "Residences", "Mortician", "Bank", "Hotel", "Tailor", "Gunsmith", "General_Store", "Sheriff", "Well", "Gate", "Wall"};
public Town(List<Building> buildings)
{
this.buildings = buildings;
}
public void ResetTown()
{
int i = 0;
foreach (Building building in buildings)
{
building.Name = buildingNames[i].ToString();
building.Level = 0;
i++;
}
}
public IEnumerator<Building> GetEnumerator()
{
return buildings.GetEnumerator();
}
}
public class Building
{
public string Name {get; set;}
public int Level {get; set;}
}