using NCC.Dependency; using NCC.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.Json; namespace NCC.ClayObject.Extensions { /// /// 字典类型拓展类 /// [SuppressSniffer] public static class DictionaryExtensions { /// /// 将对象转成字典 /// /// /// public static IDictionary ToDictionary(this object input) { if (input == null) return default; if (input is IDictionary dictionary) return dictionary; if (input is Clay clay && clay.IsObject) { var dic = new Dictionary(); foreach (KeyValuePair item in (dynamic)clay) { dic.Add(item.Key, item.Value is Clay v ? v.ToDictionary() : item.Value); } return dic; } if (input is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object) { return jsonElement.ToObject() as IDictionary; } var properties = input.GetType().GetProperties(); var fields = input.GetType().GetFields(); var members = properties.Cast().Concat(fields.Cast()); return members.ToDictionary(m => m.Name, m => GetValue(input, m)); } /// /// 将对象转字典类型,其中值返回原始类型 Type 类型 /// /// /// public static IDictionary> ToDictionaryWithType(this object input) { if (input == null) return default; if (input is IDictionary dictionary) return dictionary.ToDictionary( kvp => kvp.Key, kvp => kvp.Value == null ? new Tuple(typeof(object), kvp.Value) : new Tuple(kvp.Value.GetType(), kvp.Value) ); var dict = new Dictionary>(); // 获取所有属性列表 foreach (var property in input.GetType().GetProperties()) { dict.Add(property.Name, new Tuple(property.PropertyType, property.GetValue(input, null))); } // 获取所有成员列表 foreach (var field in input.GetType().GetFields()) { dict.Add(field.Name, new Tuple(field.FieldType, field.GetValue(input))); } return dict; } /// /// 获取成员值 /// /// /// /// private static object GetValue(object obj, MemberInfo member) { if (member is PropertyInfo info) return info.GetValue(obj, null); if (member is FieldInfo info1) return info1.GetValue(obj); throw new ArgumentException("Passed member is neither a PropertyInfo nor a FieldInfo."); } /// /// 获取指定键的值,不存在则按指定委托添加值 /// /// 字典键类型 /// 字典值类型 /// 要操作的字典 /// 指定键名 /// 添加值的委托 /// 获取到的值 public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func addFunc) { if (dictionary.TryGetValue(key, out TValue value)) { return value; } return dictionary[key] = addFunc(); } } }