在C#中打印列表对象的所有属性,可以通过反射(Reflection)来实现。以下是一个示例代码,展示了如何遍历并打印一个对象列表的所有属性及其值:
using System;
using System.Collections.Generic;
using System.Reflection;
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int YearPublished { get; set; }
}
public class Program
{
public static void Main()
{
// 创建一个Book对象的列表
List<Book> bookList = new List<Book>
{
new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", YearPublished = 1925 },
new Book { Title = "1984", Author = "George Orwell", YearPublished = 1949 }
};
// 打印列表中所有对象的所有属性
PrintProperties(bookList);
}
private static void PrintProperties(List<object> objectList)
{
foreach (var obj in objectList)
{
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
Console.WriteLine($"Object of type: {type.Name}");
foreach (PropertyInfo property in properties)
{
Console.WriteLine($"{property.Name}: {property.GetValue(obj)}");
}
Console.WriteLine();
}
}
}
这个方法适用于需要调试或记录对象状态的场景,例如:
通过这种方式,你可以灵活地打印任何对象列表的所有属性,而不需要硬编码属性名称。
领取专属 10元无门槛券
手把手带您无忧上云