[英]Iterate through web.config
我的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
}
}
使用界面。 如果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
}
}
您可以只創建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 */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.