From 17eece6838a0aeadf3664355a653492956cc273f Mon Sep 17 00:00:00 2001 From: Usagirei Date: Thu, 1 Mar 2018 23:20:14 -0300 Subject: [PATCH] Config Wrapper Class --- BepInEx/BepInEx.csproj | 1 + BepInEx/ConfigWrapper.cs | 78 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 BepInEx/ConfigWrapper.cs diff --git a/BepInEx/BepInEx.csproj b/BepInEx/BepInEx.csproj index 493f183..c80250e 100644 --- a/BepInEx/BepInEx.csproj +++ b/BepInEx/BepInEx.csproj @@ -60,6 +60,7 @@ + diff --git a/BepInEx/ConfigWrapper.cs b/BepInEx/ConfigWrapper.cs new file mode 100644 index 0000000..7944b9e --- /dev/null +++ b/BepInEx/ConfigWrapper.cs @@ -0,0 +1,78 @@ +using System.ComponentModel; + +namespace BepInEx +{ + public class ConfigWrapper + { + private TypeConverter _converter; + + public T Default { get; protected set; } + + public bool Exists + { + get { return GetKeyExists(); } + } + + public string Key { get; protected set; } + + public string Section { get; protected set; } + + public T Value + { + get { return GetValue(); } + set { SetValue(value); } + } + + public ConfigWrapper(string key, T @default = default(T)) + { + Default = @default; + Key = key; + } + + public ConfigWrapper(string key, BaseUnityPlugin plugin, T @default = default(T)) : this(key, @default) + { + Section = plugin.ID; + } + + public ConfigWrapper(string key, string section, T @default = default(T)) : this(key, @default) + { + Section = section; + } + + protected virtual bool GetKeyExists() + { + return Config.HasEntry(Key, Section); + } + + protected virtual T GetValue() + { + if (_converter == null) + _converter = TypeDescriptor.GetConverter(typeof(T)); + + if (!Exists) + return Default; + + var strVal = Config.GetEntry(Key, Section); + return (T)_converter.ConvertFrom(strVal); + } + + protected virtual void SetValue(T value) + { + if (_converter == null) + _converter = TypeDescriptor.GetConverter(typeof(T)); + + var strVal = _converter.ConvertToString(value); + Config.SetEntry(Key, strVal, Section); + } + + public static void RegisterTypeConverter() where TC : TypeConverter + { + TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC))); + } + + public void Clear() + { + Config.UnsetEntry(Key, Section); + } + } +}