.net - 需要创建一个也保存类型的动态 ConfigurationSection

标签 .net configurationsection system.configuration

我需要创建一个配置部分,它能够在 app.config 文件中存储键值对,并且无论其类型如何,都可以在运行时添加键值对。该值保持其原始类型也很重要。我需要扩展以下接口(interface)

public interface IPreferencesBackend
{
    bool TryGet<T>(string key, out T value);
    bool TrySet<T>(string key, T value); 
}

在运行时,我可以这样说:

My.Foo.Data data = new My.Foo.Data("blabla");
Pref pref = new Preferences();
pref.TrySet("foo.data", data); 
pref.Save();

My.Foo.Data date = new My.Foo.Data();
pref.TryGet("foo.data", out data);

我尝试使用 System.Configuration.Configuration.AppSettings,但问题在于它将键值对存储在字符串数组中。

我需要的是 System.Configuration.ConfigurationSection 的实现,我可以在其中控制单个设置的序列化方式。我注意到 Visual Studio 生成的设置可以执行此操作。它使用反射来创建所有设置键。我需要的是动态地执行此运行时操作。

[System.Configuration.UserScopedSettingAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Configuration.DefaultSettingValueAttribute("2008-09-24")]
public global::System.DateTime DateTime {
   get {
        return ((global::System.DateTime)(this["DateTime"]));
       }
   set {
        this["DateTime"] = value;
       }
 }

最佳答案

Phil Haack 有一篇关于 Creating Custom Configuration Sections 的精彩文章

关于.net - 需要创建一个也保存类型的动态 ConfigurationSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/125470/

相关文章:

c# - 每个配置文件的部分只能出现一次!为什么?

c# - 在 Configuration.Save() 上保留格式

c# - ConfigurationElementCollection 具有许多不同类型的 ConfigurationElements

c# - 需要默认访问器 : Custom ConfigurationSection

c# - 如何更改远程配置文件中的配置源值

c# - 如何使用 Microsoft.Management.Infrastructure (MMI) 而不是 System.Management 进行本地 WMI 查询

c# - 如何从数据库中选择最频繁的项目?

.net - .Net应用程序中极端私有(private)字节使用分析, native 内存泄漏?

c# - 即使此 Func<> 变量为空,是什么导致内存分配?

c# - 是否可以使用匹配结果的反向引用作为另一个捕获组的匹配?