RuntimeHelpersAbstraction.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using System;
  3. #if UNITY_2018_3_OR_NEWER
  4. using UnityEngine;
  5. #endif
  6. namespace Cysharp.Threading.Tasks.Internal
  7. {
  8. internal static class RuntimeHelpersAbstraction
  9. {
  10. // If we can use RuntimeHelpers.IsReferenceOrContainsReferences(.NET Core 2.0), use it.
  11. public static bool IsWellKnownNoReferenceContainsType<T>()
  12. {
  13. return WellKnownNoReferenceContainsType<T>.IsWellKnownType;
  14. }
  15. static bool WellKnownNoReferenceContainsTypeInitialize(Type t)
  16. {
  17. // The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
  18. if (t.IsPrimitive) return true;
  19. if (t.IsEnum) return true;
  20. if (t == typeof(DateTime)) return true;
  21. if (t == typeof(DateTimeOffset)) return true;
  22. if (t == typeof(Guid)) return true;
  23. if (t == typeof(decimal)) return true;
  24. // unwrap nullable
  25. if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
  26. {
  27. return WellKnownNoReferenceContainsTypeInitialize(t.GetGenericArguments()[0]);
  28. }
  29. #if UNITY_2018_3_OR_NEWER
  30. // or add other wellknown types(Vector, etc...) here
  31. if (t == typeof(Vector2)) return true;
  32. if (t == typeof(Vector3)) return true;
  33. if (t == typeof(Vector4)) return true;
  34. if (t == typeof(Color)) return true;
  35. if (t == typeof(Rect)) return true;
  36. if (t == typeof(Bounds)) return true;
  37. if (t == typeof(Quaternion)) return true;
  38. if (t == typeof(Vector2Int)) return true;
  39. if (t == typeof(Vector3Int)) return true;
  40. #endif
  41. return false;
  42. }
  43. static class WellKnownNoReferenceContainsType<T>
  44. {
  45. public static readonly bool IsWellKnownType;
  46. static WellKnownNoReferenceContainsType()
  47. {
  48. IsWellKnownType = WellKnownNoReferenceContainsTypeInitialize(typeof(T));
  49. }
  50. }
  51. }
  52. }