我想在我的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,Qualified Name Type Name" /> </MyMainSection>
我已经定义了以下代码:
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 */ } }
此属性TheAddElement应该是IEnumerable< AddElement>或者只是AddElement,如果我想允许多个添加元素?
解决方法
也没有,你会引入一个新的
ConfigurationCollectionElement,例如
部分
class MyMainSection : ConfigurationSection { [ConfigurationProperty("",Isrequired=true,IsDefaultCollection=true)] public AddElementCollection Instances { get { return (AddElementCollection) this[""]; } set { this[""] = value; } } }
采集
public class AddElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new AddElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((AddElement) element).Name; } }
元件
private class AddElement: ConfigurationElement { [ConfigurationProperty("name",IsKey=true,Isrequired=true)] public string Name { get { return (string) base["name"]; } set { base["name"] = value; } ... }