有没有一种方法可以在应用程序设置中使用字典或XML?

4
我需要在应用程序设置中存储一个复杂类型。我认为将其存储为XML会最好地工作。
问题是我不知道如何存储XML。我更喜欢将其存储为托管的XML,而不是使用仅带有原始XML字符串并需要在每次访问时解析它。我设法将设置的“Type”列设置为XDocument,但我无法设置其值。
是否有一种方法可以在应用程序设置中使用XDocument或XML?
更新
我找到了一种方法,只需使用xml编辑器编辑.settings文件即可。
我将其更改为自定义可序列化字典,但在尝试访问设置属性时出现以下错误(我将其设置为默认值的序列化表示)。
The property 'Setting' could not be created from it's default value.
Error message: There is an error in XML document (1, 41).

非常感谢您的想法和建议。

2个回答

2
我最终选择了使用.NET Fx中内置的配置类,因为这是最简单的方法。即使下面的代码是用C#编写的,你也应该能够轻松地将其转换为VB.NET(或者将其编辑并编译成一个程序集,然后从你的项目中引用它)。你会注意到,ConfigurationElementCollection类可以很容易地转换为键值对字典(你可能需要使用反射来获取值对,或者你想要存储为值对的类可能需要以ConfigurationElement为构造函数参数继承设置类)。
// ConfigurationElement.cs
public class ConfigurationElement : System.Configuration.ConfigurationElement
{
    protected T GetValue<T>(string key, T defaultValue)
    {
        var value = default(T);
        if (base[key] != null)
        {
            var str = base[key].ToString();
            try
            {
                if (!String.IsNullOrEmpty(str))
                    value = (T)Convert.ChangeType(str, typeof(T));
            }
            catch // use the default
            {
            }
        }

        return value;
    }
}

// ConfigurationElementCollection.cs
public abstract class ConfigurationElementCollection<TElement,TKey> : 
    ConfigurationElementCollection, 
    IEnumerable<TElement> where TElement : System.Configuration.ConfigurationElement, new()
{
    public TElement this[int index]
    {
        get { return (TElement)BaseGet(index); }
    }

    public TElement this[TKey key]
    {
        get { return (TElement)BaseGet(key); }
    }

    protected override System.Configuration.ConfigurationElement CreateNewElement()
    {
        return new TElement();
    }

    protected override object GetElementKey(System.Configuration.ConfigurationElement element)
    {
        return GetElementKey((TElement)element);
    }
    protected abstract TKey GetElementKey(TElement element);

    public TKey[] GetAllKeys()
    {
        var keys = BaseGetAllKeys();
        var ret = new TKey[keys.Length];
        for (var i = 0; i < keys.Length; i++)
            ret[i] = (TKey)keys[i];

        // done
        return ret; 
    }
    public void Add(TElement element)
    {
        BaseAdd(element);
    }
    public void Remove(TElement element)
    {
        BaseRemove(element);
    }
    public void Clear()
    {
        BaseClear();
    }

    IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
    {
        foreach (TElement element in this)
        {
            yield return element;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new System.NotImplementedException();
    }
}

以下是一个示例,我在我们系统中使用上述基础类代码来实现分片策略(名称已更改以保护隐私):

<!-- web.config -->
<!-- ... -->
<configuration>
    <configSections>
        <section name="sharding" type="Domain.ShardingSection, Domain.Configuration" />
    </configSections>
</configuration>
<!-- ... -->
<sharding>
    <configurationMappings>
        <add lastDigit="0" sqlMapFileName="Shard-0.SqlMap.config" />
        <add lastDigit="1" sqlMapFileName="Shard-1.SqlMap.config" />
        <add lastDigit="2" sqlMapFileName="Shard-2.SqlMap.config" />
        <add lastDigit="3" sqlMapFileName="Shard-3.SqlMap.config" />
        <add lastDigit="4" sqlMapFileName="Shard-4.SqlMap.config" />
        <add lastDigit="5" sqlMapFileName="Shard-5.SqlMap.config" />
        <add lastDigit="6" sqlMapFileName="Shard-6.SqlMap.config" />
        <add lastDigit="7" sqlMapFileName="Shard-7.SqlMap.config" />
        <add lastDigit="8" sqlMapFileName="Shard-8.SqlMap.config" />
        <add lastDigit="9" sqlMapFileName="Shard-9.SqlMap.config" />
    </configurationMappings>
</sharding>

然后是由上面的XML实例表示的配置类:

// ShardElement.cs
public class ShardElement : ConfigurationElement
{
    [ConfigurationProperty("lastDigit", IsKey=true, IsRequired=true)]
    public int LastDigit
    {
        get { return (int)this["lastDigit"]; }
    }

    [ConfigurationProperty("sqlMapFileName", IsRequired=true)]
    public string SqlMapFileName
    {
        get { return (string)this["sqlMapFileName"]; }
    }
}

// ShardElementCollection.cs
public class ShardElementCollection : ConfigurationElementCollection<ShardElement, int>
{
    protected override int GetElementKey(ShardElement element)
    {
        return element.LastDigit;
    }
}

 // ShardingSection.cs
 public class ShardingSection : ConfigurationSection
{
    public const string Name = "sharding";

    [ConfigurationProperty("configurationMappings")]
    public ShardingElementCollection ConfigurationMappings
    {
        get { return (ShardingElementCollection)base["configurationMappings"]; }
    }
}

虽然在*.config文件中使用IDictionary并不能完全胜任工作,但如果您的配置文件在运行时更新,您无需重新启动应用程序或重置AppPool即可获得新值。

2
我所做的(即使我不太喜欢,但有效)是:
我创建了可序列化的简单类来存储我的值:
<Xml.Serialization.XmlRoot("Rooms")> _
Public Class Rooms : Inherits List(Of Room)
End Class

<Serializable()> _
Public Class Room
    Private m_Room As String
    Public Property Room() As String
        Get
            Return m_Room
        End Get
        Set(ByVal value As String)
            m_Room = value
        End Set
    End Property

    Private m_Sections As New List(Of Section)
    Public ReadOnly Property Sections() As List(Of Section)
        Get
            Return m_Sections
        End Get
    End Property
End Class

<Serializable()> _
Public Class Section
    Private m_Section As String
    Public Property Section() As String
        Get
            Return m_Section
        End Get
        Set(ByVal value As String)
            m_Section = value
        End Set
    End Property
End Class

然后在.settings文件中,我编辑了设置的类型(使用xml编辑器打开.setting文件),将其更改为房间的全名(即MyProject.Rooms)。然后我创建了一个反序列化示例,并将其复制到.settings编辑器中的值字段中,以获得默认值。它非常好用。虽然它不是字典,但我仍然可以在Rooms类中实现一个内部字典(通过Room.Room返回Sections)。
如果有好的想法,仍然欢迎提出,我仍在寻找一种在.settings文件中使用IDictionary的方法。
此外,我已经为此打开了一个连接(connection),请支持一下!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接