c# - 包含子元素集合的配置元素

标签 c# configuration web-config app-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>

我定义了以下代码:

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 */
    }

}

这个属性应该TheAddElementIEnumerable<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; 
    }
    ...
}

关于c# - 包含子元素集合的配置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857362/

相关文章:

c# - 在 WPF ListView ItemTemplate 中查找子元素

c# - Topshelf 中托管的 WCF 服务需要很长时间才能关闭

ios - 在 MDM 中更新安装在 iOS 设备中的配置文件

tomcat - 在 Web 上哪里可以找到 Tomcat 托管的 WAR

asp.net-mvc - ASP.NET MVC 中何时调用 Session_End()?

WCF:是否可以在服务的 Web.config 中指定默认客户端配置设置?

c# - 如何使用 UIView.hidden 属性更改 View 的可见性

c# 从我的自定义应用程序拖放到记事本

ios - 组合 scep 和 mdm 有效负载时出错 - 注册服务器未提供有效的身份证书

c# - 从逗号分隔的字符串中读取 Web.config 设置