Tools.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Avalonia.Controls;
  8. using MessagePack;
  9. using MessagePack.Resolvers;
  10. using ShakerApp.Models;
  11. namespace ShakerApp.Tools
  12. {
  13. public static class Tools
  14. {
  15. public static string GetUnit(this Models.TimeDomainType type)
  16. {
  17. return (type.GetType()?
  18. .GetField(type.ToString())?
  19. .GetCustomAttributes<TimeDomainUnitAttribute>()
  20. .FirstOrDefault())?.Unit ?? "";
  21. }
  22. private static MessagePackSerializerOptions options = TypelessContractlessStandardResolver.Options.WithOmitAssemblyVersion(true);
  23. public static byte[] GetBytes<T>(this T value)
  24. {
  25. return MessagePack.MessagePackSerializer.Serialize(value,options);
  26. }
  27. public static T GetValue<T>(this byte[] data)
  28. {
  29. return MessagePackSerializer.Deserialize<T>(data,options);
  30. }
  31. public static T? ReadConfig<T>(this string configPath)
  32. {
  33. try
  34. {
  35. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(System.IO.File.ReadAllText(configPath));
  36. }
  37. catch
  38. {
  39. }
  40. return default;
  41. }
  42. public static void SaveConfig<T>(this T? value,string configPath)
  43. {
  44. value = value ?? default;
  45. try
  46. {
  47. if (System.IO.File.Exists(configPath)) System.IO.File.Delete(configPath);
  48. System.IO.File.WriteAllText(configPath, Newtonsoft.Json.JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented));
  49. }
  50. catch
  51. {
  52. }
  53. }
  54. static Dictionary<RuntimeTypeHandle, Control> ViewCache = new Dictionary<RuntimeTypeHandle, Control>();
  55. public static T CreateView<T>(bool cache = true)where T:Control
  56. {
  57. if(cache)
  58. {
  59. Type t = typeof(T);
  60. if (ViewCache.TryGetValue(t.TypeHandle, out var control)) return (T)control;
  61. else
  62. {
  63. ViewCache[t.TypeHandle] = Activator.CreateInstance<T>();
  64. return (T)ViewCache[t.TypeHandle];
  65. }
  66. }
  67. else
  68. {
  69. return Activator.CreateInstance<T>();
  70. }
  71. }
  72. public static Control CreateView(Type type, bool cache = true)
  73. {
  74. if (cache)
  75. {
  76. if (ViewCache.TryGetValue(type.TypeHandle, out var control)) return control;
  77. else
  78. {
  79. ViewCache[type.TypeHandle] = (Control)Activator.CreateInstance(type)!;
  80. return ViewCache[type.TypeHandle];
  81. }
  82. }
  83. else
  84. {
  85. return (Control)Activator.CreateInstance(type)!;
  86. }
  87. }
  88. }
  89. }