是否有 API 用于获取原始 Properties.Settings?

Is there an API for getting original Properties.Settings?

当您访问例如:

Properties.Settings.Default.myColor

您实际上会得到 myColor 值的当前设置,而不是程序开发期间设置的原始值。

我正在寻找它 -- 最初设置为默认值的值。删除当前设置后可以再次看到它们。

当然,我正在寻找 API 来获取这些值而不删除当前设置。

我没有找到任何现有的 API 但我需要它...

  1. 我让 VS 为整个设置创建界面(在用户部分,而不是设计器):

    internal sealed partial class Settings : ISettings
    

这只是为了更方便地使用两种设置(当前和默认)

  1. 界面是这样的:

    internal interface ISettings
    {
      bool AskForNewDescription { get;  }
      ...
    
  2. 我创建了默认设置 class:

    internal sealed class DefaultSettings : ISettings
    {
      public bool AskForNewDescription => GetDefault<bool>();
    
  3. 我没有对所有可能的情况进行测试,但它对我有用:

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

您可以通过 属性 名称找到设置 属性 的默认值,方法如下:

var value = (string)Properties.Settings.Default.Properties["propertyName"].DefaultValue;

但是 returned 值是 属性 值的 string 表示,例如,如果您查看 Settings.Designer.cs,您将看到 属性 装饰有一个存储默认值 [DefaultSettingValueAttribute("128, 128, 255")] 的属性。在这种情况下,上述代码的 return 值将是 "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");