Ich habe meine eigenen benutzerdefinierten Konfigurationsabschnitte, möchte aber ein neues Element erstellen, das einfache Schlüssel/Werte enthält. Jetzt habe ich eine funktionierende Version, aber es scheint eine Menge Code für solch eine einfachere Aufgabe zu sein. Gibt es eine verbesserte Art, Dinge zu tun?Wie definiert man einen grundlegenden benutzerdefinierten Konfigurationsabschnitt?
Unten ist eine abgespeckte Version meiner Konfigurations- und Konfigurationsklasse.
web.config
<myRootNode>
<myNode>
<add key="a" value="" />
<add key="b" value="" />
<add key="c" value="" />
...
</myNode>
...any other nodes
</myRootNode>
Benutzerdefinierte Konfiguration Klasse
public class MyRootNode : ConfigurationSection
{
[ConfigurationProperty("myNode")]
public MyNodeElement MyNode
{
get { return (MyNodeElement)this["myNode"]; }
}
}
[ConfigurationCollection(typeof(BaseElement), AddItemName = "add")]
public class MyNodeElement : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new BaseElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((BaseElement)element).Key;
}
public BaseElement this[int index]
{
get { return this.BaseGet(index) as BaseElement; }
}
}
public class BaseElement : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true, IsKey = true)]
public string Key
{
get { return this["key"].ToString(); }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return this["value"].ToString(); }
}
}
Versuchen Sie diesen Artikel: [Schreiben von benutzerdefinierten Konfigurationseinstellungen Abschnitt in C#] (http://www.codearsenal.net/2012/10/writing-custom-configuration-section-in-csharp.html) –