81 lines
2.6 KiB
C#
81 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
|
|
namespace PhxhSDK
|
|
{
|
|
public partial class Utils
|
|
{
|
|
public static Dictionary<string, object> PropertiesNameValue2ObjectDictionary(object obj)
|
|
{
|
|
var dict = new Dictionary<string, object>();
|
|
|
|
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<string, string> PropertiesNameValue2Dictionary<T>(T data) where T : class
|
|
{
|
|
Dictionary<string, string> parameters = new Dictionary<string, string>();
|
|
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<string, string> 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<string, TEnum> EnumToDictionary<TEnum>() where TEnum : Enum
|
|
{
|
|
Dictionary<string, TEnum> enumDictionary = new Dictionary<string, TEnum>();
|
|
Type enumType = typeof(TEnum);
|
|
|
|
foreach (var enumValue in Enum.GetValues(enumType))
|
|
{
|
|
string key = Enum.GetName(enumType, enumValue);
|
|
enumDictionary.Add(key, (TEnum)enumValue);
|
|
}
|
|
|
|
return enumDictionary;
|
|
}
|
|
}
|
|
} |