1

我的 web.config 部分安排如下:

<Section>
  <service1>
    <add name="Web" info="xyz"/>     
  </service1>
  <service2>
    <add name="App" info="xyz"/>     
  </service2>
  <service3>
    <add name="Data" info="xyz"/>     
  </service3>  
</Section>

我使用以下方法遍历了每个元素:

var mySection = (Sections)ConfigurationManager.GetSection("Section");

foreach (SectionsElement element in mySection.service1)
foreach (SectionsElement element in mySection.service2)
foreach (SectionsElement element in mySection.service3)

然而,这需要在每个 foreach 中复制大量代码,因为它们或多或少地执行相同的操作。有什么想法可以概括这个迭代吗?


编辑:设法通过创建对象列表来解决这个问题。

var allservices = new List<object>(){
  mySection.service1,
  mySection.service2,
  mySection.service3
}

然后迭代:

foreach (IEnumerable service in allservices)
  {
    foreach (SectionsElement element in service)
    {
      //repetitive code
    }
  }
4

2 回答 2

1

使用接口。如果mySection.service1,.service2.service3实现相同的接口,比如说IMyService,您可以轻松地执行以下操作:

var services = new IMyService[] 
{ 
    mySection.service1, 
    mySection.service2, 
    mySection.service3 
};

foreach (var service in services)
{
    foreach (SectionsElement element in service)
    {
        // repetitive code
    }
}
于 2013-06-20T13:09:01.867 回答
0

您可以只创建一个 Configs 集合:

[ConfigurationProperty("Service", IsRequired = true)]
public string Service
 {
 ...
 }



public class ServiceConfigCollection : ConfigurationElementCollection
{
    public ServiceConfig this[int index]
    {
        get
        {
            return base.BaseGet(index) as ServiceConfig;
        }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }


    protected override System.Configuration.ConfigurationElement CreateNewElement()
    {
        return new ServiceConfig();
    }

    protected override object GetElementKey(System.Configuration.ConfigurationElement element)
    {
        return ((ServiceConfig)element).Service;
    }
}

public class ServiceConfigSection : ConfigurationSection
{
    [ConfigurationProperty("Entries", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(ServiceConfigCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public ServiceConfigCollection Entries
    {
        get
        {
            return (ServiceConfigCollection)base["Entries"];
        }
    }
}

在配置文件中给出:

<configSections>
  <section
    name="Services"
    type="xxx.classes.ServiceConfigSection, xxx"
    allowLocation="true"
    allowDefinition="Everywhere"
  />
</configSections>

<Services>
  <Entries>
    <add .../>
    <add .../>
  </Entries>
</Services>

然后在代码中:

var section = ConfigurationManager.GetSection("Services") as ServiceConfigSection;
/* do something with section.Entries */
于 2013-06-20T13:21:47.667 回答