我有我想要在下面做的简化版本。我有一个由SolarSystem类使用的类Planet。我想使用foreach循环为SolarSystem中的每个Planet编写orbitTimeInDays。C#枚举对象foreach
错误CS1579 foreach语句不能 型“TestEnum.SolarSystem”的变量操作,因为“TestEnum.SolarSystem”不包含 一个公共定义“的GetEnumerator”
问题是枚举,我已经阅读了几篇有关使对象成为Enumerable的文章和问题,但我似乎无法解决如何将它应用于SolarSystem,以便检查它构建的每个Planet。 (最终还会包含小行星等等,所以它不仅仅是8颗行星和冥王星。)
有人可以帮助我了解如何枚举SolarSystem。
class Program
{
static void Main(string[] args)
{
SolarSystem solarSystem = new SolarSystem();
solarSystem.mercury.orbitTimeInDays = 88;
solarSystem.venus.orbitTimeInDays = 225;
// etc...
foreach (Planet planet in solarSystem)
{
Console.WriteLine("Time taken to orbit sun (in days) : " + planet.orbitTimeInDays.ToString());
}
}
}
public class Planet
{
public double distanceFromEarth { get; set; }
public int orbitTimeInDays { get; set; }
// etc...
public Planet() { }
}
public class SolarSystem
{
public Planet mercury { get; set; }
public Planet venus { get; set; }
// etc...
public SolarSystem()
{
mercury = new Planet();
venus = new Planet();
// etc...
}
}
问题是你的行星是同一类的每一个单独的属性,你可以做到这一点,使用一些幻想,但realisitcally,你会更好地与你的solarsystem中的行星列表..也许一些其他的道具,那么你可以foreach的行星列表.. – BugFinder
一个'ForEach'循环对阵列等工作,类似的方式为'for'循环。你有一个类而不是几个属性。 –