AppExtension.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Newtonsoft.Json.Linq;
  2. using PTMedicalInsurance.Entity;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace PTMedicalInsurance.Common
  11. {
  12. public static class AppExtension
  13. {
  14. /// <summary>
  15. /// 获取交易枚举对于的code信息
  16. /// </summary>
  17. public static string GetCode(this TradeEnum tradeEnum)
  18. {
  19. Type type = tradeEnum.GetType();
  20. FieldInfo fd = type.GetField(tradeEnum.ToString());
  21. return getFieldCode(fd);
  22. }
  23. public static ModeEnum GetMode(this TradeEnum tradeEnum)
  24. {
  25. Type type = tradeEnum.GetType();
  26. FieldInfo fd = type.GetField(tradeEnum.ToString());
  27. TradeAttribute attribute = getAttribte(fd);
  28. if (attribute != null) return attribute.Mode;
  29. // 默认值
  30. return ModeEnum.REST;
  31. }
  32. public static TradeEnum GetByCode(this TradeEnum tradeEnum,string code)
  33. {
  34. Type type = tradeEnum.GetType();
  35. FieldInfo[] fds = type.GetFields();
  36. foreach (FieldInfo fd in fds)
  37. {
  38. TradeAttribute attribute = getAttribte(fd);
  39. if (code.Equals(attribute?.Code))
  40. {
  41. return (TradeEnum)fd.GetValue(tradeEnum);
  42. }
  43. }
  44. return TradeEnum.DEFAULT;
  45. }
  46. private static TradeAttribute getAttribte(FieldInfo fd)
  47. {
  48. TradeAttribute attribute = null;
  49. if (fd == null)
  50. {
  51. return attribute;
  52. }
  53. var attributes = fd.GetCustomAttributes(typeof(TradeAttribute), false);
  54. if (attributes != null && attributes.Length == 1)
  55. {
  56. attribute = attributes.Single() as TradeAttribute;
  57. return attribute;
  58. }
  59. return attribute;
  60. }
  61. public static string Text(this JToken jtoken)
  62. {
  63. if (jtoken == null) return string.Empty;
  64. return jtoken.ToString();
  65. }
  66. public static int Int(this JToken jtoken)
  67. {
  68. if (jtoken == null) return 0;
  69. return int.Parse(jtoken.ToString());
  70. }
  71. private static string getFieldCode(FieldInfo fd)
  72. {
  73. TradeAttribute attribute = getAttribte(fd);
  74. return attribute?.Code;
  75. }
  76. public static void Extend(this JObject jObject,string key,object value)
  77. {
  78. if (jObject != null && !jObject.ContainsKey(key))
  79. {
  80. jObject.Add(key, new JValue(value));
  81. }
  82. }
  83. }
  84. }