Code: Select all
public enum SettingNames
{
Name1,
Name2,
Name3
}
public static class Settings
{
public static readonly Dictionary SettingTypes = new()
{
{ SettingNames.Name1, typeof(Type1) }
{ SettingNames.Name2, typeof(Type2) }
{ SettingNames.Name3, typeof(Type3) }
}
public static void Save(SettingNames setting, object value)
{
Type registeredType = SettingTypes[setting];
if (registeredType != value.GetType()) throw new Exception("Value type does not match registered type for this setting")
// Serialize
}
public static bool Load(SettingNames setting, ref object value)
{
Type registeredType = SettingTypes[setting];
if (registeredType != value.GetType()) throw new Exception("Value type does not match registered type for this setting")
// Deserialize - if successful, assign result to value and return true
}
}
public class MyClass
{
public Type1 Property1 {get; set;} = new Type1();
private void SaveProperties()
{
Settings.Save(SettingNames.Name1, Property1);
}
private void LoadProperties()
{
object property1 = new Type1();
bool success = Settings.Load(SettingNames.Name1, ref property1)
if (success)
Property1 = property1;
}
}
Code: Select all
public static void Save(SettingNames setting, T value) where T : SettingTypes[setting]