using System; using System.Collections.Generic; using System.Reflection; namespace PhxhSDK { public partial class Utils { public static Dictionary PropertiesNameValue2ObjectDictionary(object obj) { var dict = new Dictionary(); if (obj == null) { return dict; } var type = obj.GetType(); var properties = type.GetProperties(); foreach (PropertyInfo property in properties) { object value = property.GetValue(obj, null); dict.Add(property.Name, value); } return dict; } public static Dictionary PropertiesNameValue2Dictionary(T data) where T : class { Dictionary parameters = new Dictionary(); var properties = typeof(T).GetProperties(); foreach (var property in properties) { AddPropertyToDictionary(typeof(T).Name, property, data, parameters); } return parameters; } private static void AddPropertyToDictionary(string outerObjectPrefix, PropertyInfo property, object obj, Dictionary parameters) { var propertyValue = property.GetValue(obj); if (propertyValue == null) { return; } var name = string.IsNullOrEmpty(outerObjectPrefix) ? property.Name : $"{outerObjectPrefix}_{property.Name}"; if (property.PropertyType.IsClass && property.PropertyType != typeof(string)) { var nestedProperties = property.PropertyType.GetProperties(); foreach (var nestedProperty in nestedProperties) { AddPropertyToDictionary(name, nestedProperty, propertyValue, parameters); } } else { parameters.Add(name, propertyValue.ToString()); } } public static Dictionary EnumToDictionary() where TEnum : Enum { Dictionary enumDictionary = new Dictionary(); Type enumType = typeof(TEnum); foreach (var enumValue in Enum.GetValues(enumType)) { string key = Enum.GetName(enumType, enumValue); enumDictionary.Add(key, (TEnum)enumValue); } return enumDictionary; } } }