代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace 打印类
{
internal class Program
{
static void Main(string[] args)
{
List<Dog> dogs = new List<Dog>()
{
new Dog { Name = "Max", Age = 3, Breed = "Labrador" },
new Dog { Name = "Bella", Age = 2, Breed = "Poodle" },
new Dog { Name = "Charlie", Age = 4, Breed = "Bulldog" }
};
foreach (var dog in dogs)
{
Type type = dog.GetType();
PropertyInfo[] properties = type.GetProperties();
List<string> allProperty = new List<string>();
foreach (var property in properties)
{
string value = $"{property.Name}: {property.GetValue(dog)}";
allProperty.Add(value);
}
string content = string.Join(",", allProperty);
Console.WriteLine(content);
}
Console.ReadKey();
}
}
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public string Breed { get; set; }
}
}
运行
进行一个简单的封装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace 打印类
{
internal class Program
{
static void Main(string[] args)
{
List<Dog> dogs = new List<Dog>()
{
new Dog { Name = "Max", Age = 3, Breed = "Labrador" },
new Dog { Name = "Bella", Age = 2, Breed = "Poodle" },
new Dog { Name = "Charlie", Age = 4, Breed = "Bulldog" }
};
PrintClass(dogs);
Console.ReadKey();
}
/// <summary>
/// 打印一个 List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static void PrintClass<T>(List<T> list)
{
foreach (var item in list)
{
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
List<string> allProperty = new List<string>();
foreach (var property in properties)
{
string value = $"{property.Name}: {property.GetValue(item)}";
allProperty.Add(value);
}
string content = string.Join(",", allProperty);
Console.WriteLine(content);
}
}
}
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public string Breed { get; set; }
}
}
运行:
效果是一样的,这时候,可以传任意类型的 List
其实还可以进一步封装,让其可以打印 List<类> ,也可以直接打印类
/// <summary>
/// 打印一个 List 类的所有公共属性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static void PrintClass<T>(List<T> list)
{
foreach (var item in list)
{
PrintClass(item);
}
}
/// <summary>
/// 打印一个类的所有公共属性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
public static void PrintClass<T>(T item)
{
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
List<string> allProperty = new List<string>();
foreach (var property in properties)
{
string value = $"{property.Name}: {property.GetValue(item)}";
allProperty.Add(value);
}
string content = string.Join(",", allProperty);
Console.WriteLine(content);
}
end