我需要按照优先顺序将对象列表存储到配置部分。
如果我使用扩展ConfigurationElementCollection和ConfigurationElement的标准实现(类似于描述here)。将配置文件读取并写入?
时,是否会保留集合的顺序编辑:一些示例代码。
鉴于此:
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>
当我访问代码中的事物列表时,它是否保证与配置中指定的顺序相同?