如何迭代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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图避免这一行中的显式属性名称
Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
Run Code Online (Sandbox Code Playgroud)
这样,如果我的Galaxy类具有比 和 更多的属性Name,MegaLightYears它也会自动打印它们。
如果你想
Type以通用方式将其用于任何您可以编写一个Reflection像这样的快速实用程序
public static string GetAllProperties(object obj)
{
return string.Join(" ", obj.GetType()
.GetProperties()
.Select(prop => prop.GetValue(obj)));
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
foreach (Galaxy theGalaxy in theGalaxies)
{
Console.WriteLine(GetAllProperties(theGalaxy));
}
Run Code Online (Sandbox Code Playgroud)