c# - 是否有用于获取原始 Properties.Settings 的 API?

标签 c# .net winforms settings

当您访问例如:

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/

相关文章:

c# - 在 C# 中通过 ID 动态删除 <tr> 标签

c# - 如何在 C# windows 应用程序中将数据 gridview 条目中的记录插入到 SQL 数据库?

c# - 复制 Http 请求 InputStream

.net - 插值字符串 $ 被视为无效字符并返回错误 BC30037 (vb.net)

c# - 为什么 12 X 8.33 似乎等于大约 105?

c# - 具有异步/等待方法调试的 Visual Studio 源服务器

c# - 我在哪里可以找到 WPF 中的免费蒙版 TextBox?

.net - 如何通过将 .cs 文件作为脚本执行来避免编写 .bat 文件?

winforms - 从数据绑定(bind)的 DevExpress CheckedListBoxControl 获取项目索引

c# - 带有十进制数字的蒙面文本框