1

我需要按优先顺序将对象列表存储到配置部分。

如果我使用扩展 ConfigurationElementCollection 和 ConfigurationElement 的标准实现(类似于此处描述的内容)。读取和写入配置文件时会保留集合的顺序吗?

编辑:一些示例代码。

鉴于这种:

class Program
{
    static void Main(string[] args)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var section = config.GetSection("TestSection") as TestSection;
        foreach (MyElement item in section.HopefullyOrderedItems)
        {
            Console.WriteLine(item.ElementValue);
        }
        Console.ReadLine();
    }
}

public class TestSection : ConfigurationSection
{
    [ConfigurationProperty("ListOfThings")]
    [ConfigurationCollection(typeof(MyCollection))]
    public MyCollection HopefullyOrderedItems
    {
        get { return (MyCollection) this["ListOfThings"]; }
        set { this["ListOfThings"] = value; }
    }

}

public class MyCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((MyElement) element).ElementValue;
    }

    new public MyElement this[string name]
    {
        get { return (MyElement) BaseGet(name); }
    }
}

public class MyElement : ConfigurationElement
{
    [ConfigurationProperty("ElementValue")]
    public string ElementValue
    {
        get { return (string) this["ElementValue"]; }
        set { this["ElementValue"] = value; }
    }
}

有了这个 app.config:

<configuration>
    <configSections>
        <section name="TestSection" type="testestes.TestSection, testestes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
    </configSections>
    <TestSection>
        <ListOfThings>
            <add ElementValue="qwerty" />
            <add ElementValue="asdfgh" />
        </ListOfThings>
    </TestSection>
</configuration>

当我访问代码中的事物列表时,它是否保证与配置中指定的顺序相同?

4

0 回答 0