如何迭代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
,则会自动打印它们。
答案 0 :(得分:3)
如果我理解正确你想避免在循环中写下星系的各个属性吗?
在这种情况下,您可能会ToString
适当地重载Galaxy
:
class Galaxy {
public override string ToString() {
return Name + " " + MegaLightYearsl;
}
}
然后你可以做
foreach (var galaxy in theGalaxies) {
Console.WriteLine(galaxy);
}
但是,由于您只有一个ToString
要覆盖,因此您不能对不同上下文中可能需要的对象的字符串表示形式做差异。
答案 1 :(得分:2)
如果你想
Type
您可以像这样编写一个快速Reflection
实用程序
public static string GetAllProperties(object obj)
{
return string.Join(" ", obj.GetType()
.GetProperties()
.Select(prop => prop.GetValue(obj)));
}
并像
一样使用它foreach (Galaxy theGalaxy in theGalaxies)
{
Console.WriteLine(GetAllProperties(theGalaxy));
}
答案 2 :(得分:0)
您的问题有点不清楚,但我假设您要求您按索引而不是foreach
循环遍历列表。
尝试标准for
循环,如下所示:
for(int i = 0; i < theGalaxies.Count; i++) {
Console.WriteLine(theGalaxies[i].Name + " " + theGalaxies[i].MegaLightYears);
}