ParseHelper.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace TheraBytes.BetterUi.Editor
  7. {
  8. public delegate bool TryParseDelegate<T>(string input, out T result);
  9. public static class ParseHelper
  10. {
  11. const string NULL_STRING = "<null>";
  12. public static bool TryParse<T>(string input, out T result)
  13. {
  14. Type type = typeof(T);
  15. if(type == typeof(string))
  16. {
  17. if (input == NULL_STRING)
  18. result = default(T);
  19. result = (T)(object)input;
  20. return true;
  21. }
  22. if (TryParseExplicitType<bool, T>(input, bool.TryParse, out result))
  23. return true;
  24. if (TryParseExplicitType<int, T>(input, int.TryParse, out result))
  25. return true;
  26. if (TryParseExplicitType<float, T>(input, float.TryParse, out result))
  27. return true;
  28. if (TryParseExplicitType<Vector2, T>(input, TryParseVector2, out result))
  29. return true;
  30. Debug.LogError("No TryParse method defined for type " + type.Name);
  31. return false;
  32. }
  33. private static bool TryParseExplicitType<T, U>(string input, TryParseDelegate<T> tryParseMethod, out U result)
  34. {
  35. T innerResult;
  36. if (tryParseMethod(input, out innerResult))
  37. {
  38. result = (U)(object)innerResult;
  39. return true;
  40. }
  41. result = default(U);
  42. return false;
  43. }
  44. public static string ToParsableString<T>(T value)
  45. {
  46. if(typeof(T) == typeof(string))
  47. {
  48. if (value == null)
  49. return NULL_STRING;
  50. return value.ToString();
  51. }
  52. if(value is bool || value is int || value is float)
  53. {
  54. return value.ToString();
  55. }
  56. if (value is Vector2)
  57. {
  58. Vector2 v2 = (Vector2)(object)value;
  59. return string.Format("{0}:{1}", v2.x, v2.y);
  60. }
  61. throw new NotImplementedException();
  62. }
  63. static bool TryParseVector2(string input, out Vector2 result)
  64. {
  65. string[] parts = input.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  66. if (parts.Length != 2)
  67. {
  68. result = default(Vector2);
  69. return false;
  70. }
  71. float x, y;
  72. if(!float.TryParse(parts[0], out x) || !float.TryParse(parts[1], out y))
  73. {
  74. result = default(Vector2);
  75. return false;
  76. }
  77. result = new Vector2(x, y);
  78. return true;
  79. }
  80. }
  81. }