Dav*_*vid 5 c# settings configuration
我有自己的自定义配置部分,但想创建一个内部具有简单键/值的新元素.现在我有一个工作版本,但似乎有很多代码用于这么简单的任务.是否有改进的做事方式?
下面是我的配置和自定义配置类的剥离版本.
web.config中
<myRootNode>
<myNode>
<add key="a" value="" />
<add key="b" value="" />
<add key="c" value="" />
...
</myNode>
...any other nodes
</myRootNode>
Run Code Online (Sandbox Code Playgroud)
自定义配置类
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(); }
}
}
Run Code Online (Sandbox Code Playgroud)
zvo*_*kov 10
我猜是这样的:
<configSections>
<section name="validationXsds" type="System.Configuration.DictionarySectionHandler, System" />
</configSections>
<validationXsds>
<add key="http://schemas.xmlsoap.org/soap/envelope/" value="http://dev.ei.directv.com/schemas/xmlsoap/envelope.xsd"/>
<add key="http://schemas.xmlsoap.org/soap/encoding/" value="http://dev.ei.directv.com/schemas/xmlsoap/encoding.xsd"/>
<add key="http://ei.directv.com/schemas/envelope/v3_0" value="http://dev.ei.directv.com/schemas/envelope/v3.0/Envelope.xsd"/>
</validationXsds>
IDictionary xsds = (IDictionary)WebConfigurationManager.GetSection("validationXsds");
Run Code Online (Sandbox Code Playgroud)
更新:在.NET 4.0中我正在使用
type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
Run Code Online (Sandbox Code Playgroud)
手动执行此操作需要花费太多精力.您可以让Visual Studio使用Configuration Section Designer加载项为您创建该部分.