ConvertUtil.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using PaySharp.Core;
  4. using PaySharp.Core.Utils;
  5. namespace PaySharp.Wechatpay
  6. {
  7. internal static class ConvertUtil
  8. {
  9. public static List<T> ToList<T, TChildren>(GatewayData gatewayData, int index)
  10. {
  11. var flag = true;
  12. var list = new List<T>();
  13. var i = 0;
  14. while (flag)
  15. {
  16. var type = typeof(T);
  17. var obj = Activator.CreateInstance(type);
  18. var properties = type.GetProperties();
  19. var isFirstProperty = true;
  20. foreach (var item in properties)
  21. {
  22. if (item.PropertyType == typeof(List<TChildren>))
  23. {
  24. var chidrenList = ToList<TChildren, object>(gatewayData, i);
  25. item.SetValue(obj, chidrenList);
  26. continue;
  27. }
  28. string key;
  29. var renameAttribute = item.GetCustomAttributes(typeof(ReNameAttribute), true);
  30. if (renameAttribute.Length > 0)
  31. {
  32. key = ((ReNameAttribute)renameAttribute[0]).Name;
  33. }
  34. else
  35. {
  36. key = item.Name.ToSnakeCase();
  37. }
  38. if (index > -1)
  39. {
  40. key += $"_{index}";
  41. }
  42. key += $"_{i}";
  43. var value = gatewayData.GetStringValue(key);
  44. if (value == null)
  45. {
  46. if (isFirstProperty)
  47. {
  48. flag = false;
  49. break;
  50. }
  51. continue;
  52. }
  53. isFirstProperty = false;
  54. item.SetValue(obj, Convert.ChangeType(value, item.PropertyType));
  55. }
  56. if (!flag)
  57. {
  58. return list;
  59. }
  60. list.Add((T)obj);
  61. i++;
  62. }
  63. return list;
  64. }
  65. }
  66. }