2011-09-21 254 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節點實現的,但命名空間的意圖是將其抽象出來。