GRPCObjectExtensions.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Google.Protobuf.WellKnownTypes;
  2. using System;
  3. using System.Linq;
  4. namespace XYY.Common.GRPC.Standard
  5. {
  6. public static class GRPCObjectExtensions
  7. {
  8. public static T FromGrpc<T>(this object grpcObj) where T : class
  9. {
  10. if (grpcObj == null) throw new ArgumentNullException("参数不能为null");
  11. T toData = Activator.CreateInstance<T>();
  12. var properties = toData.GetType().GetProperties().Where(p => p.PropertyType.IsPublic && p.CanWrite).ToList();
  13. var grcpPs = grpcObj.GetType().GetProperties();
  14. foreach (var grpcProperties in grcpPs)
  15. {
  16. var toPro = properties.FirstOrDefault(x => x.Name.Equals(grpcProperties.Name, StringComparison.OrdinalIgnoreCase));
  17. var grpcVal = grpcProperties.GetValue(grpcObj, null);
  18. if (toPro != null)
  19. {
  20. if (toPro.PropertyType == grpcProperties.PropertyType)
  21. toPro.SetValue(toData, grpcVal, null);
  22. else
  23. {
  24. if (grpcProperties.PropertyType == typeof(Timestamp) && grpcVal != null)
  25. {
  26. if (toPro.PropertyType == typeof(DateTime?) || toPro.PropertyType == typeof(DateTime))
  27. {
  28. Timestamp timeStamp = (Timestamp)grpcVal;
  29. toPro.SetValue(toData, timeStamp.ToDateTime().ToLocalTime(), null);
  30. }
  31. }
  32. }
  33. }
  34. }
  35. return toData;
  36. }
  37. public static T ToGrpc<T>(this object obj)
  38. {
  39. if (obj == null) throw new ArgumentNullException("参数不能为null");
  40. T toGrpc = Activator.CreateInstance<T>();
  41. var toRpcProperties = toGrpc.GetType().GetProperties().Where(p => p.PropertyType.IsPublic && p.CanWrite).ToList();
  42. var objData = obj.GetType().GetProperties();
  43. foreach (var objPro in objData)
  44. {
  45. var toRpcPro = toRpcProperties.FirstOrDefault(x => x.Name.Equals(objPro.Name, StringComparison.OrdinalIgnoreCase));
  46. var objVal = objPro.GetValue(obj, null);
  47. if (toRpcPro != null && objVal != null)
  48. {
  49. if (toRpcPro.PropertyType == objPro.PropertyType)
  50. toRpcPro.SetValue(toGrpc, objVal, null);
  51. else
  52. {
  53. if (toRpcPro.PropertyType == typeof(Timestamp) && objVal != null)
  54. {
  55. if (objPro.PropertyType == typeof(DateTime?))
  56. {
  57. DateTime? datetime = (DateTime?)objVal;
  58. DateTime setDateTime = datetime.Value.ToUniversalTime();
  59. toRpcPro.SetValue(toGrpc, Timestamp.FromDateTime(setDateTime), null);
  60. }
  61. else if (objPro.PropertyType == typeof(DateTime))
  62. {
  63. DateTime datetime = (DateTime)objVal;
  64. DateTime setDateTime = datetime.ToUniversalTime();
  65. toRpcPro.SetValue(toGrpc, Timestamp.FromDateTime(setDateTime), null);
  66. }
  67. }
  68. }
  69. }
  70. }
  71. return toGrpc;
  72. }
  73. }
  74. }