如何将Properties.Settings.Default的副本保存到变量?

chr*_*rus 3 c# settings winforms

我在选项对话框中有一个"恢复默认值"按钮,并且只想恢复在此表单中受影响的值,而不是整个Properties.Settings.Default

所以我尝试过:

var backup = Properties.Settings.Default;
Properties.Settings.Default.Reload();
overwriteControls();
Properties.Settings.Default = backup;
Run Code Online (Sandbox Code Playgroud)

但遗憾的是,由于备份似乎也发生了变化,因此无法正常工作Reload()?为什么以及如何正确地执行此操作?

cra*_*mes 5

Settings类使用单例模式,这意味着它们在任何时候都只能是一个设置实例.因此,制作该实例的副本将始终引用同一个实例.

理论上,您可以使用反射迭代Settings类中的每个属性,并提取如下所示的值:

        var propertyMap = new Dictionary<string, object>();

        // backup properties
        foreach (var propertyInfo in Properties.Settings.Default.GetType().GetProperties())
        {
            if (propertyInfo.CanRead && propertyInfo.CanWrite && propertyInfo.GetCustomAttributes(typeof(UserScopedSettingAttribute), false).Any())
            {
                var name = propertyInfo.Name;
                var value = propertyInfo.GetValue(Properties.Settings.Default, null);
                propertyMap.Add(name, value);
            }
        }

        // restore properties
        foreach (var propertyInfo in Properties.Settings.Default.GetType().GetProperties())
        {
            if (propertyInfo.CanRead && propertyInfo.CanWrite && propertyInfo.GetCustomAttributes(typeof(UserScopedSettingAttribute), false).Any())
            {
                var value = propertyMap[propertyInfo.Name];
                propertyInfo.SetValue(Properties.Settings.Default, value, null);                    
            }
        }
Run Code Online (Sandbox Code Playgroud)

虽然,它有点icky,如果您的设置很复杂,可能需要一些工作.您可能想重新考虑您的策略.您可以只在按下"确定"按钮后提交值,而不是将值恢复为默认值.无论哪种方式,我认为您将需要将每个值复制到属性的属性基础上的某个临时位置.