C#学习教程:阅读C#中的默认应用程序设置其中大部分是颜色设置。我有一个表单,用户可以在其中自定义这些颜色,我想添加一个按钮来恢复默认颜色设置。如何读取默认设置?例如:我在Properties.Settings中有一个名为CellBackgroundColor的用户设置。在设计时,我使用IDE将Color.White的值设置为Color.White。用户在我的程序CellBackgroundColor中将Color.Black设置为Color.Black。我使用Properties.Settings.Default.Save()来保存设置。用户单击恢复默认颜色按钮。Properties.Settings.Default.CellBackgroundColor现在返回Color.Black。我如何返回Color.White?@ozgur,Settings.Default.Properties["property"].DefaultValue//来自配置文件的初始值示例:stringfoo=Settings.Default.Foo;//默认情况下Foo="Foo"Settings.Default.Foo="Boo";设置.默认.保存();字符串modifiedValue=Settings.Default.Foo;//modifiedValue="Boo"stringoriginalValue=Settings.Default.Properties["Foo"].DefaultValueasstring;//originalValue="Foo"阅读“Windows2.0FormsProgramming”,我偶然发现了这两个在这种情况下可能有用的方法:ApplicationSettingsBase.ReloadApplicationSettingsBase.Reset来自MSDN:Reload与Reset对比,前者将加载最后一组saves,它将加载保存的默认值。所以用法是:Properties.Settings.Default.Reset()Properties.Settings.Default.Reload()我不确定这是必要的,必须有更简洁的方法,否则希望有人觉得这有用;公共静态类SettingsPropertyCollectionExtensions{publicstaticTGetDefault(thisSettingsPropertyCollectionme,stringproperty){stringval_string=(string)Settings.Default.Properties[property].DefaultValue;返回(T)Convert.ChangeType(val_string,typeof(T));}}用法;varsetting=Settings.Default.Properties.GetDefault("MySetting");Properties.Settings.Default.Reset()会将所有设置重置为其原始值。我如何返回到Color.White?您可以采用两种方式:我用两套设置解决了这个问题。我使用VisualStudio默认为当前设置添加的设置,即Properties.Settings.Default。但我还在项目“项目->添加新项->常规->设置文件”中添加了另一个设置文件,并将实际默认值存储在那里,即Properties.DefaultSettings.Default。然后我确保我从不写入Properties.DefaultSettings.Default设置,只从中读取。将所有内容更改回默认值只是将当前值设置回默认值的一种情况。我发现调用ApplicationSettingsBase.Reset会将设置重置为默认值,但也会保存它们。我想要的行为是将它们重置为默认值但不保存它们(这样如果用户不喜欢默认值,他们可以在保存之前恢复它们)。我写了一个适合我目的的扩展方法:以上是C#学习教程:阅读C#Shared中默认应用程序设置的全部内容,如果对大家有用需要进一步了解C#学习教程,希望请注意——usingSystem;使用系统配置;命名空间YourApplication.Extensions{publicstaticclassExtensionsApplicationSettingsBase{publicstaticvoidLoadDefaults(thisApplicationSettingsBasethat){foreach(SettingsPropertysettingsPropertyinthat.Properties){that[settingsProperty.Name]=Convert.ChangeType(settingsProperty.DefaultValue,settingsProperty.PropertyType);}}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
