ConfigurationElementCollection中的无密钥元素

时间:2014-10-28 19:18:28

标签: c# .net configuration config custom-configuration

继承ConfigurationElementCollection:

public class Directories : ConfigurationElementCollection
{
    ...
}

ConfigurationElementCollection需要GetElementKey(System.Configuration.ConfigurationElement)的实施。

但我不关心密钥,因为我有这样的自定义配置部分:

<directorySection>
  <directories>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\0" dropOffDirectory="C:\Users\User\Documents\DropOff\0"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\0" dropOffDirectory="C:\Users\User\Documents\DropOff\0"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\1" dropOffDirectory="C:\Users\User\Documents\DropOff\1"/>
    <directory pickUpDirectory="C:\Users\User\Documents\PickUp\2" dropOffDirectory="C:\Users\User\Documents\DropOff\2"/>
  </directories>
</directorySection>

它可以有多个元素,每个元素都是无密钥的,这个结构应该允许重复(如上所述)。那么在这种情况下该怎么做呢?

1 个答案:

答案 0 :(得分:0)

尝试像这样使用ObjectIDGenerator

[ConfigurationCollection(typeof(SchedulerTaskItem), AddItemName = "Task")]
public class SchedulerTaskCollection: ConfigurationElementCollection
{
    private static readonly ObjectIDGenerator idGenerator = new ObjectIDGenerator();

    protected override ConfigurationElement CreateNewElement()
    {
        return new SchedulerTaskItem();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        bool firstTime;
        return idGenerator.GetId(element, out firstTime);
    }
}