例如,当您访问时:
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");
我没有找到任何现有的 API,但我需要它......
-
我制作了VS来为整个设置创建界面(在用户部分,而不是设计器(:
internal sealed partial class Settings : ISettings
这只是为了更轻松地使用两种设置(当前和默认(
-
接口如下所示:
internal interface ISettings { bool AskForNewDescription { get; } ...
-
我创建了默认设置类:
internal sealed class DefaultSettings : ISettings { public bool AskForNewDescription => GetDefault<bool>();
-
我没有对所有可能的情况进行测试,但它对我有用:
private readonly ISettings source; private string GetSerialized(string name) { var prop = this.source.GetType().GetProperty(name); foreach (object attr in prop.GetCustomAttributes(true)) { var val_attr = attr as DefaultSettingValueAttribute; if (val_attr != null) return val_attr.Value; } return null; } private T GetDefault<T>([CallerMemberName] string name = null) { string s = GetSerialized(name); if (s == null) return default(T); TypeConverter tc = TypeDescriptor.GetConverter(typeof(T)); return (T)tc.ConvertFromString(s); }