ObjectExtensions.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace Grpc.Extension.Common
  5. {
  6. internal static class ObjectExtensions
  7. {
  8. public static object FillProp(this object src)
  9. {
  10. foreach (var p in src.GetType().GetTypeInfo().GetProperties())
  11. {
  12. try
  13. {
  14. if (p.PropertyType.GetTypeInfo().IsPrimitive ||
  15. p.PropertyType.GetTypeInfo().Equals(typeof(string)) ||
  16. p.PropertyType.GetTypeInfo().Equals(typeof(DateTime)) ||
  17. p.PropertyType.GetTypeInfo().Equals(typeof(Decimal)) ||
  18. p.PropertyType.GetTypeInfo().Equals(typeof(Guid)) ||
  19. p.PropertyType.GetTypeInfo().Equals(typeof(DateTimeOffset)) ||
  20. p.PropertyType.GetTypeInfo().Equals(typeof(TimeSpan)))
  21. {
  22. continue;
  23. }
  24. if (GrpcExtensionsOptions.Instance.FillPropExcludePrefixs.Any(q => p.PropertyType.GetTypeInfo().FullName.StartsWith(q)))
  25. {
  26. continue;
  27. }
  28. var subSrc = Activator.CreateInstance(p.PropertyType);
  29. subSrc = FillProp(subSrc);
  30. p.SetValue(src, subSrc);
  31. }
  32. catch
  33. {
  34. continue;
  35. }
  36. }
  37. return src;
  38. }
  39. }
  40. }