2011-09-21 93 views
0

我没有与配置文件interactiong太多的经验和我读MSDN中的GetSection()方法,该报告指出:什么是“配置类型”?

**Notes to Implementers**: 

    You must cast the return value to the expected configuration type. 
To avoid possible casting exceptions, you should use a conditional 
casting operation such as... 

什么是“配置型”本说明是什么意思?选择的部分不是代表一个xml节点吗?

回答

1

配置类型基本上是你定义来代表你想在App.config或Web.Config中

存储的配置值自定义类的只是类型

您的自定义配置部分需要从System.Configuration.ConfigurationSection当继承您使用GetSection方法,你需要将返回值转换为你继承了断System.Configuration.ConfigurationSection

看到您的自定义类的类型更here

一个例子是,如果我有一个特殊的类代表我想无论是在App.Config中或Web.Config中,如存储属性:

public class MyConfig : ConfigurationSection 
{ 
    [ConfigurationProperty("myConfigProp", DefaultValue = "false", IsRequired = false)] 
    public Boolean MyConfigProp 
    { 
     get 
     { 
      return (Boolean)this["myConfigProp"]; 
     } 
     set 
     { 
      this["myConfigProp"] = value; 
     } 
    } 
} 

任何时候,我会想访问该财产,我会做在我的代码如下:

//create a MyConfig object from the XML in my App.Config file 
MyConfig config = (MyConfig)System.Configuration.ConfigurationManager.GetSection("myConfig"); 

//access the MyConfigProp property 
bool test = config.MyConfigProp; 
+0

很好的解释!谢谢! – pencilCake

1

有一些伟大的样品在MSDN上的位置:http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

在这里,“配置型”,是指已建立扩大ConfigurationSection自定义类型。是的,这是作为XML节点实现的,但命名空间的意图是将其抽象出来。