Enums.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Text;
  5. #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE
  6. using System.Collections;
  7. using System.Reflection;
  8. #endif
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
  11. {
  12. internal abstract class Enums
  13. {
  14. internal static Enum GetEnumValue(System.Type enumType, string s)
  15. {
  16. if (!IsEnumType(enumType))
  17. throw new ArgumentException("Not an enumeration type", "enumType");
  18. // We only want to parse single named constants
  19. if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0)
  20. {
  21. s = s.Replace('-', '_');
  22. s = s.Replace('/', '_');
  23. #if NETCF_1_0
  24. FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public);
  25. if (field != null)
  26. {
  27. return (Enum)field.GetValue(null);
  28. }
  29. #else
  30. return (Enum)Enum.Parse(enumType, s, false);
  31. #endif
  32. }
  33. throw new ArgumentException();
  34. }
  35. internal static Array GetEnumValues(System.Type enumType)
  36. {
  37. if (!IsEnumType(enumType))
  38. throw new ArgumentException("Not an enumeration type", "enumType");
  39. #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
  40. IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  41. FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
  42. foreach (FieldInfo field in fields)
  43. {
  44. // Note: Argument to GetValue() ignored since the fields are static,
  45. // but Silverlight for Windows Phone throws exception if we pass null
  46. result.Add(field.GetValue(enumType));
  47. }
  48. object[] arr = new object[result.Count];
  49. result.CopyTo(arr, 0);
  50. return arr;
  51. #else
  52. return Enum.GetValues(enumType);
  53. #endif
  54. }
  55. internal static Enum GetArbitraryValue(System.Type enumType)
  56. {
  57. Array values = GetEnumValues(enumType);
  58. int pos = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length;
  59. return (Enum)values.GetValue(pos);
  60. }
  61. internal static bool IsEnumType(System.Type t)
  62. {
  63. #if NEW_REFLECTION || NETFX_CORE
  64. return t.GetTypeInfo().IsEnum;
  65. #else
  66. return t.IsEnum;
  67. #endif
  68. }
  69. }
  70. }
  71. #pragma warning restore
  72. #endif