05 Nov
2006

Generische ConfigurationElementCollection

 

Baut man sich für seine .NET 2.0 Anwendung eigene Konfigurationsbereiche, dann braucht man früher oder später auch eine Liste von Elementen. Braucht man dies öfters, dann wird es ein wenig nervig, da man ein wenig Grundtipparbeit für jede Auflistung hat. Hier ein generischer Ansatz für ConfigurationElementCollection.

public abstract class ConfigurationElementCollection<T> : ConfigurationElementCollection
        where T : ConfigurationElement
{
    protected override ConfigurationElement CreateNewElement()
    {
        return (ConfigurationElement)Activator.CreateInstance(typeof(T));
    }

    public T this[int index]
    {
        get { return (T)base.BaseGet(index); }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    public new T this[string key]
    {
        get { return (T)base.BaseGet(key); }
    }
}

Nun braucht man nur noch ein ConfigurationElement. Hier ein Beispiel aus einer aktuellen Anwendung von mir.

public class EntryObjectSettings : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return (string) base["name"]; }
        set { base["name"] = value; }
    }

    [ConfigurationProperty("type", IsRequired = true)]
    [TypeConverter(typeof (TypeTypeConverter))]
    [SubclassTypeValidator(typeof (BaseEntry))]
    public Type Type
    {
        get { return (Type) base["type"]; }
        set { base["type"] = value; }
    }

    [ConfigurationProperty("template", IsRequired = false)]
    [FileExistsValidator]
    public string Template
    {
        get { return (string) base["template"]; }
        set { base["template"] = value; }
    }
}

Jetzt erstellt man eine ConfigurationElementCollection für sein ConfigurationElement zu. Das einzige was nun noch gemacht werden muss, ist das überschreiben von GetElementKey() damit die Collection auch einen eindeutigen Key für jeden Eintrag erhält.

[ConfigurationCollection(typeof (EntryObjectSettings))]
public class EntryObjectSettingsCollection : ConfigurationElementCollection
{
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((EntryObjectSettings) element).Name;
    }
}
    

Der Eintrag ist mir etwas Wert
 
Comments have been closed on this topic.