public static class ObjectToDictionaryConverter
{// 将对象转换为字典
public static Dictionary<string, object>ConvertObjectToDictionary(this object obj){
var dictionary = new Dictionary<string, object>();// 获取对象的类型
Type type = obj.GetType();// 获取对象的所有字段
FieldInfo[] fields = type.GetFields();foreach(var field in fields){
dictionary[field.Name]=GetFieldValue(field, obj);}// 获取对象的所有属性
PropertyInfo[] properties = type.GetProperties();foreach(var property in properties){
dictionary[property.Name]=GetPropertyValue(property, obj);}return dictionary;}// 获取字段值并处理集合
private static object GetFieldValue(FieldInfo field, object obj){
var value = field.GetValue(obj);returnProcessValue(value);}// 获取属性值并处理集合
private static object GetPropertyValue(PropertyInfo property, object obj){
var value = property.GetValue(obj);returnProcessValue(value);}// 处理集合类型和普通值
private static object ProcessValue(object value){if(value is IEnumerable<object> collection){// 如果是集合,则递归转换每个元素
var list = new List<Dictionary<string, object>>();foreach(var item in collection){
list.Add(ConvertObjectToDictionary(item));// 递归调用转换方法}return list;}return value;// 非集合类型直接返回}}