ConfigWrapper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.ComponentModel;
  3. namespace BepInEx
  4. {
  5. public class ConfigWrapper<T>
  6. {
  7. private readonly Func<string, T> _strToObj;
  8. private readonly Func<T, string> _objToStr;
  9. private readonly string _defaultStr;
  10. public string Key { get; protected set; }
  11. public string Section { get; protected set; }
  12. public T Value
  13. {
  14. get { return GetValue(); }
  15. set { SetValue(value); }
  16. }
  17. public ConfigWrapper(string key, T @default = default(T))
  18. {
  19. var cvt = TypeDescriptor.GetConverter(typeof(T));
  20. if (!cvt.CanConvertFrom(typeof(string)))
  21. throw new ArgumentException("Default TypeConverter can't convert from String");
  22. if (!cvt.CanConvertTo(typeof(string)))
  23. throw new ArgumentException("Default TypeConverter can't convert to String");
  24. _strToObj = (str) => (T)cvt.ConvertFromInvariantString(str);
  25. _objToStr = (obj) => cvt.ConvertToInvariantString(obj);
  26. _defaultStr = _objToStr(@default);
  27. Key = key;
  28. }
  29. public ConfigWrapper(string key, Func<string, T> strToObj, Func<T, string> objToStr, T @default = default(T))
  30. {
  31. if (objToStr == null)
  32. throw new ArgumentNullException("objToStr");
  33. if (strToObj == null)
  34. throw new ArgumentNullException("strToObj");
  35. _strToObj = strToObj;
  36. _objToStr = objToStr;
  37. _defaultStr = _objToStr(@default);
  38. Key = key;
  39. }
  40. public ConfigWrapper(string key, BaseUnityPlugin plugin, T @default = default(T))
  41. : this(key, @default)
  42. {
  43. Section = plugin.ID;
  44. }
  45. public ConfigWrapper(string key, BaseUnityPlugin plugin, Func<string, T> strToObj, Func<T, string> objToStr, T @default = default(T))
  46. : this(key, strToObj, objToStr, @default)
  47. {
  48. Section = plugin.ID;
  49. }
  50. public ConfigWrapper(string key, string section, T @default = default(T))
  51. : this(key, @default)
  52. {
  53. Section = section;
  54. }
  55. public ConfigWrapper(string key, string section, Func<string, T> strToObj, Func<T, string> objToStr, T @default = default(T))
  56. : this(key, strToObj, objToStr, @default)
  57. {
  58. Section = section;
  59. }
  60. protected virtual bool GetKeyExists()
  61. {
  62. return Config.HasEntry(Key, Section);
  63. }
  64. protected virtual T GetValue()
  65. {
  66. var strVal = Config.GetEntry(Key, _defaultStr, Section);
  67. return _strToObj(strVal);
  68. }
  69. protected virtual void SetValue(T value)
  70. {
  71. var strVal = _objToStr(value);
  72. Config.SetEntry(Key, strVal, Section);
  73. }
  74. public void Clear()
  75. {
  76. Config.UnsetEntry(Key, Section);
  77. }
  78. }
  79. }