You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 5 години
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. using IronPython.Runtime;
  5. namespace MQTTnet.Server.Scripting
  6. {
  7. public static class PythonConvert
  8. {
  9. public static object ToPython(object value)
  10. {
  11. if (value is PythonDictionary)
  12. {
  13. return value;
  14. }
  15. if (value is string)
  16. {
  17. return value;
  18. }
  19. if (value is int)
  20. {
  21. return value;
  22. }
  23. if (value is float)
  24. {
  25. return value;
  26. }
  27. if (value is bool)
  28. {
  29. return value;
  30. }
  31. if (value is IDictionary dictionary)
  32. {
  33. var pythonDictionary = new PythonDictionary();
  34. foreach (DictionaryEntry dictionaryEntry in dictionary)
  35. {
  36. pythonDictionary.Add(dictionaryEntry.Key, ToPython(dictionaryEntry.Value));
  37. }
  38. return pythonDictionary;
  39. }
  40. if (value is IEnumerable enumerable)
  41. {
  42. var pythonList = new List();
  43. foreach (var item in enumerable)
  44. {
  45. pythonList.Add(ToPython(item));
  46. }
  47. return pythonList;
  48. }
  49. return value;
  50. }
  51. public static string Pythonfy(Enum value)
  52. {
  53. return Pythonfy(value.ToString());
  54. }
  55. public static string Pythonfy(string value)
  56. {
  57. var result = new StringBuilder();
  58. foreach (var @char in value)
  59. {
  60. if (char.IsUpper(@char) && result.Length > 0)
  61. {
  62. result.Append('_');
  63. }
  64. result.Append(char.ToLowerInvariant(@char));
  65. }
  66. return result.ToString();
  67. }
  68. public static TEnum ParseEnum<TEnum>(string value) where TEnum : Enum
  69. {
  70. return (TEnum)Enum.Parse(typeof(TEnum), value.Replace("_", string.Empty), true);
  71. }
  72. }
  73. }