ConfigWrapper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.ComponentModel;
  2. namespace BepInEx
  3. {
  4. public class ConfigWrapper<T>
  5. {
  6. private TypeConverter _converter;
  7. public T Default { get; protected set; }
  8. public bool Exists
  9. {
  10. get { return GetKeyExists(); }
  11. }
  12. public string Key { get; protected set; }
  13. public string Section { get; protected set; }
  14. public T Value
  15. {
  16. get { return GetValue(); }
  17. set { SetValue(value); }
  18. }
  19. public ConfigWrapper(string key, T @default = default(T))
  20. {
  21. Default = @default;
  22. Key = key;
  23. }
  24. public ConfigWrapper(string key, BaseUnityPlugin plugin, T @default = default(T)) : this(key, @default)
  25. {
  26. Section = TypeLoader.GetMetadata(plugin).GUID;
  27. }
  28. public ConfigWrapper(string key, string section, T @default = default(T)) : this(key, @default)
  29. {
  30. Section = section;
  31. }
  32. protected virtual bool GetKeyExists()
  33. {
  34. return Config.HasEntry(Key, Section);
  35. }
  36. protected virtual T GetValue()
  37. {
  38. if (_converter == null)
  39. _converter = TypeDescriptor.GetConverter(typeof(T));
  40. if (!Exists)
  41. return Default;
  42. var strVal = Config.GetEntry(Key, null, Section);
  43. return (T)_converter.ConvertFrom(strVal);
  44. }
  45. protected virtual void SetValue(T value)
  46. {
  47. if (_converter == null)
  48. _converter = TypeDescriptor.GetConverter(typeof(T));
  49. var strVal = _converter.ConvertToString(value);
  50. Config.SetEntry(Key, strVal, Section);
  51. }
  52. public static void RegisterTypeConverter<TC>() where TC : TypeConverter
  53. {
  54. TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
  55. }
  56. public void Clear()
  57. {
  58. Config.UnsetEntry(Key, Section);
  59. }
  60. }
  61. }