技术开发 频道

揭开.NET 2.0配置隐藏的秘密

  8、自定义配置节组

  根据你致力于的项目类型或者特定于你的应用程序的配置需求,你可能会觉得使用配置节组更有用。.NET 2.0提供了便利的配置功能来完成这事,之前我们讨论的ASP.NET的配置组就是。创建一个配置节组比创建一个配置节更简单,但是使用和访问他们呢稍微复杂一些。假定我们有两个配置节类叫做ExampleSection 和AnotherSection,我们可以像这样写成一个配置组:

代码public sealed class ExampleSectionGroup: ConfigurationSectionGroup

  {

  
#region Constructors

  
public ExampleSectionGroup()

  {

  }

  #endregion

  
#region Properties

  [ConfigurationProperty(
"example")]

  
public ExampleSection Example

  {

  
get { return (ExampleSection)base.Sections["example"]; }

  }

  [ConfigurationProperty(
"another")]

  
public AnotherSection Another

  {

  
get { return (AnotherSection)base.Sections["another"]; }

  }

  #endregion

  }

    一旦我们有了节组代码,我们需要在.config文件中定义它。和定义一个一般的节类似,只是增加了层次级别。值得注意的是,ExampleSection 和AnotherSection现在必须作为我们配置组的子节点定义:

type="Examples.Configuration.ExampleSectionGroup,

  Examples.Configuration
">

stringValue="A sample string value."

  boolValue
="true"

  timeSpanValue
="5:00:00"

  
>

  

  dateTimeValue
="10\16\2006"

  integerValue
="1"

  
/>

      这个配置节组做了这些,使两个配置节在一个组。此外,它提供了一个访问这些节的中心点。一旦我们有一个引用指向我们的ConfigurationSectionGroup对象,我们可以访问ExampleSection 和AnotherSection,而不用再次调用ConfigurationManager.GetSection()。但是,获取最初的引用指向我们的ExampleSectionGroup并不和获取一个单独的节那样简单。专研.NET 2.0深入一点,我们将发现Configuration类。这个类直接表示一个应用程序定义在它的.config文件中的配置。跟ConfigurationManager类一样,Configuration有一个GetSection()方法,以及附加了GetSectionGroup()方法。我们可以访问配置节组和里面的配置节,例如:

代码private string m_string;

  
private bool m_bool;

  
private TimeSpan m_timespan;

  
private DateTime m_datetime;

  
private int m_int;

  void GetExampleSettings()

  {

  Configuration config
=

  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  ExampleSectionGroup group
= config.GetSectionGroup("example.group")

  
as ExampleSectionGroup;

  ExampleSection section
= group.Example;

  m_string
= section.StringValue;

  m_bool
= section.BooleanValue;

  m_timespan
= section.TimeSpanValue;

  m_datetime
= section.Nested.DateTimeValue;

  m_int
= section.Nested.IntegerValue;

  AnotherSection section2
= group.Another;

  }

    虽然上面的代码不是很复杂,要求一个Configuration对象来获得GetSectionGroup()方法不是很明显。一旦我们有一个Configuration对象,然而,你会发现一些他的额外有用的功能。在下一节中,我们将讨论用Configuration对象来将修改保存回配置文件,只要支持保存。

0
相关文章