技术开发 频道

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

  将这个元素加到我们之前创建的ExampleSection中,就像定义一个新属性一样简单。下面展示了添加一个嵌套元素的必要代码:

代码 public class ExampleSection: ConfigurationSection

  {

  
#region Constructors

  
///

  
/// Predefines the valid properties and prepares

  
/// the property collection.

  
///

  
static ExampleSection()

  {

  
// Create other properties...

  s_propElement
= new ConfigurationProperty(

  
"nestedElement",

  
typeof(NestedElement),

  null,

  ConfigurationPropertyOptions.IsRequired

  );

  s_properties
= new ConfigurationPropertyCollection();

  
// Add other properties...

  s_properties.Add(s_propElement);

  }

  #endregion

  
#region Static Fields

  
private static ConfigurationProperty s_propElement;

  
// Other static fields...

  #endregion

  
#region Properties

  
// ...

  
///

  
/// Gets the NestedElement element.

  
///

  [ConfigurationProperty(
"nestedElement")]

  
public NestedElement Nested

  {

  
get { return (NestedElement)base[s_propElement]; }

  }

  
// ...

  #endregion

  }

    最后,在我们的XML配置文件中使用这个元素只需要简单地在标记中添加标记。值得注意的是,只能有一个nestedElement实例在example中。这种方式创建的嵌套元素,不允许有类似命名的元素集合。它允许一个特定元素的单个实例,在自定义节的一个特定的嵌套深度。下一节将讲在一个配置节中定义元素集合。完整的App.config文件应该像下面这样:

<configuration>
  
<configSections>
    
<section name="example" type="Examples.Configuration.ExampleSection,
                                  Examples.Configuration" />
  </configSections>

  
<example
    stringValue
="A sample string value."
    boolValue
="true"
    timeSpanValue
="5:00:00"
  
>
    
<nestedElement
      dateTimeValue
="10/16/2006"
      integerValue
="1"
    
/>
  
</example>
</configuration>

            使用新的套元素又是非常的简单,因为Nested属性(property)将暴露给我们的前面例子中使用的节变量:

private string m_string;
private bool m_bool;
private TimeSpan m_timespan;
private DateTime m_datetime;
private int m_int;

void GetExampleSettings()
{
    ExampleSection section
= ConfigurationManager.GetSection("example")
                            
as ExampleSection;
    
if (section != null)
    {
        m_string
= section.StringValue;
        m_bool
= section.BooleanValue;
        m_timespan
= section.TimeSpanValue;
        m_datetime
= section.Nested.DateTimeValue;
        m_int
= section.Nested.IntegerValue;
    }
}

  

0
相关文章