TypeExtensionMethod.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace VCommon.VOpenApi.Docgen
  6. {
  7. public static class TypeExtensionMethod
  8. {
  9. public static string GetFriendlyTypeName(this Type type)
  10. {
  11. string fullName;
  12. if (type.IsGenericType)
  13. {
  14. var gtd = type.GetGenericTypeDefinition();
  15. var gargs = type.GetGenericArguments();
  16. var gtdFullName = gtd.FullName ?? throw new ArgumentNullException(nameof(type), "Missing full name");
  17. fullName = gtdFullName.Split('`')[0] + "[" + string.Join(",", gargs.Select(p => $"[{p.FullName}]")) + "]";
  18. }
  19. else
  20. {
  21. fullName = type.FullName ?? throw new ArgumentNullException(nameof(type), "Missing full name");
  22. }
  23. return fullName;
  24. }
  25. public static bool IsArray(this Type toCheck)
  26. {
  27. if (toCheck.IsArray) return true;
  28. return null != toCheck.GetInterface(nameof(IEnumerable));
  29. }
  30. public static bool IsDic(this Type toCheck)
  31. {
  32. return toCheck.GetInterfaces().Any(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(IDictionary<,>));
  33. }
  34. public static Type GetArrayElementType(this Type toGet)
  35. {
  36. if (toGet.IsArray) return toGet.GetElementType();
  37. var ge = toGet.GetInterfaces().FirstOrDefault(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(IEnumerable<>));
  38. return null != ge
  39. ? ge.GetGenericArguments()[0]
  40. : typeof(object);
  41. }
  42. public static bool IsPrimitiveType(this Type toCheck)
  43. {
  44. return toCheck.IsEnum
  45. || PrimitiveTypeNames.Contains(toCheck.FullName)
  46. || toCheck.IsGenericType && toCheck.GetGenericTypeDefinition() == typeof(Nullable<>) && (PrimitiveTypeNames.Contains(toCheck.GetGenericArguments()[0].FullName) || toCheck.GetGenericArguments()[0].IsEnum);
  47. }
  48. public static string GetPrimitiveTypeName(this Type type)
  49. {
  50. return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)
  51. ? type.GetGenericArguments()[0].FullName
  52. : type.FullName;
  53. }
  54. private static readonly HashSet<string> PrimitiveTypeNames = new HashSet<string>
  55. {
  56. "System.Boolean"
  57. ,"System.Byte"
  58. ,"System.SByte"
  59. ,"System.Int16"
  60. ,"System.UInt16"
  61. ,"System.Int32"
  62. ,"System.UInt32"
  63. ,"System.Int64"
  64. ,"System.UInt64"
  65. ,"System.Single"
  66. ,"System.Double"
  67. ,"System.Decimal"
  68. ,"System.Byte[]"
  69. ,"System.DateTime"
  70. ,"System.DateTimeOffset"
  71. ,"System.Guid"
  72. ,"System.String"
  73. ,"System.Object"
  74. };
  75. }
  76. }