简体   繁体   中英

Key-less elements in ConfigurationElementCollection

When you inherit ConfigurationElementCollection:

public class Directories : ConfigurationElementCollection
{
    ...
}

ConfigurationElementCollection requires an implementation for GetElementKey(System.Configuration.ConfigurationElement) .

But I don't care about keys since I have a custom configuration section like this:

<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>

It can have multiple elements, and each element is key-less, and this structure should allow for duplicates (as above). So what should I do in this case?

Try to use ObjectIDGenerator like this

[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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM