AppContextConfigHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Globalization;
  5. namespace System
  6. {
  7. internal static class AppContextConfigHelper
  8. {
  9. internal static int GetInt32Config(string configName, int defaultValue, bool allowNegative = true)
  10. {
  11. try
  12. {
  13. object config = AppContext.GetData(configName);
  14. int result = defaultValue;
  15. switch (config)
  16. {
  17. case string str:
  18. if (str.StartsWith("0x"))
  19. {
  20. result = Convert.ToInt32(str, 16);
  21. }
  22. else if (str.StartsWith("0"))
  23. {
  24. result = Convert.ToInt32(str, 8);
  25. }
  26. else
  27. {
  28. result = int.Parse(str, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo);
  29. }
  30. break;
  31. case IConvertible convertible:
  32. result = convertible.ToInt32(NumberFormatInfo.InvariantInfo);
  33. break;
  34. }
  35. return !allowNegative && result < 0 ? defaultValue : result;
  36. }
  37. catch (FormatException)
  38. {
  39. return defaultValue;
  40. }
  41. catch (OverflowException)
  42. {
  43. return defaultValue;
  44. }
  45. }
  46. internal static short GetInt16Config(string configName, short defaultValue, bool allowNegative = true)
  47. {
  48. try
  49. {
  50. object config = AppContext.GetData(configName);
  51. short result = defaultValue;
  52. switch (config)
  53. {
  54. case string str:
  55. if (str.StartsWith("0x"))
  56. {
  57. result = Convert.ToInt16(str, 16);
  58. }
  59. else if (str.StartsWith("0"))
  60. {
  61. result = Convert.ToInt16(str, 8);
  62. }
  63. else
  64. {
  65. result = short.Parse(str, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo);
  66. }
  67. break;
  68. case IConvertible convertible:
  69. result = convertible.ToInt16(NumberFormatInfo.InvariantInfo);
  70. break;
  71. }
  72. return !allowNegative && result < 0 ? defaultValue : result;
  73. }
  74. catch (FormatException)
  75. {
  76. return defaultValue;
  77. }
  78. catch (OverflowException)
  79. {
  80. return defaultValue;
  81. }
  82. }
  83. }
  84. }