技术开发 频道

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

[ConfigurationCollection(typeof(ThingElement), AddItemName="thing",
      CollectionType
=ConfigurationElementCollectionType.BasicMap)]
public class ExampleThingElementCollection: ConfigurationElementCollection
{
    
#region Constructors
    
// ...
    #endregion

    
#region Fields
    
// ...
    #endregion

    
#region Properties
    
// ...

    
public override ConfigurationElementCollectionType CollectionType
    {
        
get { return ConfigurationElementCollectionType.BasicMap; }
    }

    
protected override string ElementName
    {
        
get { return "thing"; }
    }
    #endregion

    
#region Indexers
    
// ...
    #endregion

    
#region Methods
    
// ...
    #endregion
    
    
#region Overrides
    
// ...
    #endregion
}

        这些简单的修改将更新我们的集合类为BasicMap ,这将使得在.config文件中可以使用元素<thing>添加新项,而不是<add>。现在我们可以这样修改我们的配置文件,比以前的版本更漂亮、更清楚:

<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"
    
/>
    
<things>
      
<thing name="slimy" type="goo" />
      
<thing name="metal" type="metal" color="silver" />
      
<thing name="block" type="wood" color="tan" />
    
</things>
  
</example>
</configuration>

       有时候,当我们有一个层次结构的配置,而且设置级联从一个父web.config到子web.config,我们需要控制那些元素显示在集合的前面。默认,所有元素以继承的顺序。当有多个web.config文件合并时,这种顺序不是特别好定义。通过使用替换的集合类型(译注:即BasicMapAlternateAddRemoveClearMapAlternate),我们可以控制迫使所以继承的元素被列在最后。级联三个web.config文件将以读取文件的顺序列出所有项,以最低级的web.config开始,随后是他的父web.config们,最后是根web.config。BasicMapAlternateAddRemoveClearMapAlternate都是这种方式,而且警告添加时修改父级别的web.config的项。

0
相关文章