我需要创建一个配置部分,它能够在 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/