当您访问例如:
Properties.Settings.Default.myColor
您实际上会得到 myColor
值的当前设置,而不是在程序开发期间设置的原始值。
我正在寻找它 - 最初设置为默认值的值。删除当前设置后可以再次看到它们。
当然,我正在寻找一个 API 来获取这些值而不删除当前设置。
最佳答案
您可以通过这种方式通过属性名称找到设置属性的默认值:
var value = (string)Properties.Settings.Default.Properties["propertyName"].DefaultValue;
但返回值是属性值的 string
表示,例如,如果您查看 Settings.Designer.cs
,您会看到该属性装饰有存储默认值 [DefaultSettingValueAttribute("128, 128, 255")]
的属性。在这种情况下,上述代码的返回值将是 "128, 128, 225"
。
为了能够获取原始属性类型中的默认值,我创建了以下扩展方法:
using System.ComponentModel;
using System.Configuration;
public static class SettingsExtensions
{
public static object GetDefaultValue(this ApplicationSettingsBase settings,
string propertyName)
{
var property = settings.Properties[propertyName];
var type = property.PropertyType;
var defaultValue = property.DefaultValue;
return TypeDescriptor.GetConverter(type).ConvertFrom(defaultValue);
}
}
然后作为用法:
var myColor = (Color)Properties.Settings.Default.GetDefaultValue("myColor");
关于c# - 是否有用于获取原始 Properties.Settings 的 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51149330/