Wat*_* v2 6 c# configuration app-config web-config
我想在我的web.config中有一个自定义部分,如下所示:
<MyMainSection attributeForMainSection = "value foo">
<add name = "foo"
type = "The.System.Type.Of.Foo, Assembly, Qualified Name Type Name" />
<add name = "bar"
type = "The.System.Type.Of.Bar, Assembly, Qualified Name Type Name" />
</MyMainSection>
Run Code Online (Sandbox Code Playgroud)
我已经定义了以下代码:
using System.Configuration;
class MyMainSection : ConfigurationSection
{
/*I've provided custom implemenation.
Not including it here for the sake of brevity. */
[ConfigurationProperty("attributeForMainSection")]
public string AttributeForMyMainSection { get; set; }
[ConfigurationProperty("add")]
public AddElement TheAddElement { get; set; }
private class AddElement: ConfigurationElement
{
/* Implementation done */
}
}
Run Code Online (Sandbox Code Playgroud)
这个属性TheAddElement应该是,IEnumerable<AddElement>还是只是AddElement我想允许多个添加元素?
Jam*_*mes 14
也没有,你会引入一个新的ConfigurationCollectionElement,例如
部分
class MyMainSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired=true, IsDefaultCollection=true)]
public AddElementCollection Instances
{
get { return (AddElementCollection) this[""]; }
set { this[""] = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
采集
public class AddElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new AddElement();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((AddElement) element).Name;
}
}
Run Code Online (Sandbox Code Playgroud)
元件
private class AddElement: ConfigurationElement
{
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get { return (string) base["name"]; }
set { base["name"] = value;
}
...
}
Run Code Online (Sandbox Code Playgroud)