技术开发 频道

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

  5、添加自定义元素

  默认情况下,自定义配置节中所有的配置属性(properties)在.config文件中被表示成属性(attributes)。这并不总是必然的,然而,一个更复杂XML结构,由属性(attributes)和元素(elements)混合组成的,是需要的。不要怕:.NET的配置系统完全支持自定义配置元素,他们的属性(properties)可以是属性(attributes)或者多个嵌套元素。要创建自定义配置元素,简单地写一个类继承自ConfigurationElement而不是ConfigurationSection。配置元素的执行细节跟配置节一样,不同之处是元素必须嵌套在配置节中。

  让我们继续,嵌套一个自定义元素在ExampleSection中。让我们这个嵌套元素存储一个DateTime值和一个整数值。创建这个类的代码如下所示:

using System;

  
using System.Configuration;

  #endregion

  
namespace Examples.Configuration

  {

  
///

  
/// An example configuration element class.

  
///

  
public class NestedElement: ConfigurationElement

  {

  
#region Constructors

  
///

  
/// Predefines the valid properties and prepares

  
/// the property collection.

  
///

  
static NestedElement()

  {

  
// Predefine properties here

  s_propDateTime
= new ConfigurationProperty(

  
"dateTimeValue",

  
typeof(DateTime),

  null,

  ConfigurationPropertyOptions.IsRequired

  );

  s_propInteger
= new ConfigurationProperty(

  
"integerValue",

  
typeof(int),

  
0,

  ConfigurationPropertyOptions.IsRequired

  );

  s_properties
= new ConfigurationPropertyCollection();

  s_properties.Add(s_propDateTime);

  s_properties.Add(s_propInteger);

  }

  #endregion

  
#region Static Fields

  
private static ConfigurationProperty s_propDateTime;

  
private static ConfigurationProperty s_propInteger;

  
private static ConfigurationPropertyCollection s_properties;

  #endregion

  
#region Properties

  
///

  
/// Gets the DateTimeValue setting.

  
///

  [ConfigurationProperty(
"dateTimeValue", IsRequired=true)]

  
public DateTime StringValue

  {

  
get { return (DateTime)base[s_propDateTime]; }

  }

  
///

  
/// Gets the IntegerValue setting.

  
///

  [ConfigurationProperty(
"integerValue")]

  
public int IntegerValue

  {

  
get { return (int)base[s_propInteger]; }

  }

  
///

  
/// Override the Properties collection and return our custom one.

  
///

  
protected override ConfigurationPropertyCollection Properties

  {

  
get { return s_properties; }

  }

  #endregion

  }

 

  自定义配置元素类#region Using Statements

0
相关文章