c# – 包含子元素集合的Configuration元素

前端之家收集整理的这篇文章主要介绍了c# – 包含子元素集合的Configuration元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在我的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; 
    }
    ...
}
原文链接:https://www.f2er.com/csharp/98724.html

猜你在找的C#相关文章