如何遍历 List<Galaxy>
并打印出每个属性的值,而不必显式地写出属性名?
例如,我使用以下代码来写入 galaxy
的所有属性值:
private static void IterateThroughList()
{
var theGalaxies = new List<Galaxy>
{
new Galaxy() { Name = "Tadpole", MegaLightYears = 400},
new Galaxy() { Name = "Pinwheel", MegaLightYears = 25}
};
foreach (Galaxy theGalaxy in theGalaxies)
{
// this part is of concern
Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
}
}
我试图避免在这行代码中使用明确的属性名称。
Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
因此,如果我的
Galaxy
类有比Name
和MegaLightYears
更多的属性,它也会自动打印它们。
Galaxy theGalaxy
)的声明吗? - senshin