ReflectionHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. namespace Universal;
  2. public class Property(string name, Type type, object? value)
  3. {
  4. public string Name { get; } = name;
  5. public Type TypeName { get; } = type;
  6. public object Value { get; } = value ??= "NULL";
  7. }
  8. public class ReflectionHelper
  9. {
  10. public static IEnumerable<Property> FromatDitits<T>(T model) where T : notnull
  11. {
  12. foreach (PropertyInfo propertyInfo in model.GetType().GetRuntimeProperties())
  13. yield return new(propertyInfo.Name, propertyInfo.PropertyType, propertyInfo.GetValue(model));
  14. }
  15. public static Dictionary<string, object?>? GetProperties<T>(T t)
  16. {
  17. if (t == null)
  18. return default;
  19. PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
  20. if (properties.Length <= 0)
  21. return default;
  22. Dictionary<string, object?> ListStr = [];
  23. foreach (PropertyInfo item in properties)
  24. {
  25. string name = item.Name; //名称
  26. object? value = item.GetValue(t, null); //值
  27. if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
  28. ListStr.Add(name, value);
  29. else
  30. GetProperties(value);
  31. }
  32. return ListStr;
  33. }
  34. public static Dictionary<string, object?>? GetFields<T>(T t)
  35. {
  36. if (t == null)
  37. return default;
  38. FieldInfo[] fields = t.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
  39. if (fields.Length <= 0)
  40. return default;
  41. Dictionary<string, object?> ListStr = [];
  42. foreach (FieldInfo item in fields)
  43. {
  44. string name = item.Name; //名称
  45. object? value = item.GetValue(t); //值
  46. if (item.FieldType.IsValueType || item.FieldType.Name.StartsWith("String"))
  47. ListStr.Add(name, value);
  48. else
  49. GetFields(value);
  50. }
  51. return ListStr;
  52. }
  53. }