How can I save a copy of Properties.Settings.Default to a variable?

允我心安 提交于 2019-12-22 11:11:34

问题


I have a "Restore Defaults" button in an options dialog and want to restore the values that are affected in this form only and not the whole Properties.Settings.Default

So I tried:

var backup = Properties.Settings.Default;
Properties.Settings.Default.Reload();
overwriteControls();
Properties.Settings.Default = backup;

But this unfortunately doesn't work since backup seems to change at Reload(), too? Why and how would I do this correctly?


回答1:


The Settings class uses a singleton pattern, meaning their can only ever be one instance of the settings at any one time. So making a copy of that instance will always refer to the same instance.

In theory, you could iterate over each of the properties in the Settings class using reflection and extract the values like this:

        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);                    
            }
        }

Although, it's a bit icky, and might need some work if your settings are complex. You might want to rethink your strategy. Rather than restoring the values to defaults, you could only commit the values once the OK button is pressed. Either way, I think you are going to need to copy each of the values to some temporary location on a property by property basis.



来源:https://stackoverflow.com/questions/15400742/how-can-i-save-a-copy-of-properties-settings-default-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!