假设我的配置中有以下内容:
<configSections>
<section name="interestingThings" type="Test.InterestingThingsSection, Test" />
<section name="moreInterestingThings" type="Test.InterestingThingsSection, Test" />
</configSections>
<interestingThings>
<add name="Thing1" value="Seuss" />
</interestingThings>
<moreInterestingThings>
<add name="Thing2" value="Seuss" />
</moreInterestingThings>
Run Code Online (Sandbox Code Playgroud)
如果我想获得任一部分,我可以很容易地按名称获得它们:
InterestingThingsSection interesting = (InterestingThingsSection)ConfigurationManager.GetSection("interestingThings");
InterestingThingsSection more = (InterestingThingsSection)ConfigurationManager.GetSection("moreInterestingThings");
Run Code Online (Sandbox Code Playgroud)
但是,这取决于我的代码知道该部分在配置中的命名方式 - 它可以命名为任何名称。我更喜欢的是能够InterestingThingsSection从配置中提取所有类型的部分,而不管名称如何。我怎样才能以灵活的方式解决这个问题(因此,支持应用程序配置和网络配置)?
编辑: 如果你已经Configuration有了,获取实际部分并不太难:
public static IEnumerable<T> SectionsOfType<T>(this Configuration configuration)
where T : ConfigurationSection
{
return configuration.Sections.OfType<T>().Union(
configuration.SectionGroups.SectionsOfType<T>());
}
public static IEnumerable<T> SectionsOfType<T>(this ConfigurationSectionGroupCollection collection)
where T : ConfigurationSection
{
var sections = new List<T>();
foreach (ConfigurationSectionGroup group in collection)
{
sections.AddRange(group.Sections.OfType<T>());
sections.AddRange(group.SectionGroups.SectionsOfType<T>());
}
return sections;
}
Run Code Online (Sandbox Code Playgroud)
但是,如何Configuration以普遍适用的方式获取实例?或者,我怎么知道我是否应该使用ConfigurationManager或WebConfigurationManager?
到目前为止,这似乎是最好的方法:
var config = HostingEnvironment.IsHosted
? WebConfigurationManager.OpenWebConfiguration(null) // Web app.
: ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Desktop app.
Run Code Online (Sandbox Code Playgroud)