RealWorldTerrainXMLExt.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* INFINITY CODE 2013-2019 */
  2. /* http://www.infinity-code.com */
  3. using System;
  4. using System.Globalization;
  5. using System.Reflection;
  6. using System.Xml;
  7. using UnityEngine;
  8. namespace InfinityCode.RealWorldTerrain
  9. {
  10. public static class RealWorldTerrainXMLExt
  11. {
  12. public static T GetAttribute<T>(XmlNode node, string name)
  13. {
  14. XmlAttribute attribute = node.Attributes[name];
  15. if (attribute == null) return default(T);
  16. string value = attribute.Value;
  17. if (string.IsNullOrEmpty(value)) return default(T);
  18. Type type = typeof(T);
  19. if (type == typeof(string)) return (T)Convert.ChangeType(value, type);
  20. T obj = default(T);
  21. PropertyInfo[] properties = type.GetProperties();
  22. Type underlyingType = type;
  23. #if !UNITY_WSA
  24. if (properties.Length == 2 && string.Equals(properties[0].Name, "HasValue", StringComparison.InvariantCultureIgnoreCase)) underlyingType = properties[1].PropertyType;
  25. #else
  26. if (properties.Length == 2 && string.Equals(properties[0].Name, "HasValue", StringComparison.OrdinalIgnoreCase)) underlyingType = properties[1].PropertyType;
  27. #endif
  28. try
  29. {
  30. MethodInfo method = underlyingType.GetMethod("Parse", new[] { typeof(string), typeof(IFormatProvider) });
  31. if (method != null) obj = (T)method.Invoke(null, new object[] { value, RealWorldTerrainCultureInfo.numberFormat });
  32. else
  33. {
  34. method = underlyingType.GetMethod("Parse", new[] { typeof(string) });
  35. obj = (T)method.Invoke(null, new[] { value });
  36. }
  37. }
  38. catch (Exception exception)
  39. {
  40. Debug.Log(exception.Message + "\n" + exception.StackTrace);
  41. throw;
  42. }
  43. return obj;
  44. }
  45. }
  46. }