10、配置技巧和窍门
在我研究和实验配置节的时候,我学到一些技巧,可是使他们更容易使用。自定义配置节的某些方面非常乏味,如所有时间一直通过调用ConfigurationManager.GetSection("someSectionName")获取SomeSectionClass。为了减轻繁琐乏味,我尝试在我的ConfigurationSection类中使用下列方式:
public class SomeConfigurationSection
{
static SomeConfigurationSection()
{
// Preparation...
}
// Properties...
#region GetSection Pattern
private static SomeConfigurationSection m_section;
/// <summary>
/// Gets the configuration section using the default element name.
/// </summary>
public static SomeConfigurationSection GetSection()
{
return GetSection("someConfiguration");
}
/// <summary>
/// Gets the configuration section using the specified element name.
/// </summary>
public static SomeConfigurationSection GetSection(string definedName)
{
if (m_section == null)
{
m_section = ConfigurationManager.GetSection(definedName) as
SomeConfigurationSection;
if (m_section == null)
throw new ConfigurationException("The <" + definedName +
"> section is not defined in your .config file!");
}
return m_section;
}
#endregion
}
{
static SomeConfigurationSection()
{
// Preparation...
}
// Properties...
#region GetSection Pattern
private static SomeConfigurationSection m_section;
/// <summary>
/// Gets the configuration section using the default element name.
/// </summary>
public static SomeConfigurationSection GetSection()
{
return GetSection("someConfiguration");
}
/// <summary>
/// Gets the configuration section using the specified element name.
/// </summary>
public static SomeConfigurationSection GetSection(string definedName)
{
if (m_section == null)
{
m_section = ConfigurationManager.GetSection(definedName) as
SomeConfigurationSection;
if (m_section == null)
throw new ConfigurationException("The <" + definedName +
"> section is not defined in your .config file!");
}
return m_section;
}
#endregion
}