What is "Configuration Type"?
I don't have much experience on interactiong with config files and I was reading the GetSection() method in MSDN which notes that:
**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...
What does "configuration type" mean in this note? Are not the sections selected represents an xml开发者_开发百科 node always?
Configuration Type is basically just the type of the custom class you define to represent the configuration values you want to store in the App.Config or Web.Config
Your custom config section needs to inherit from System.Configuration.ConfigurationSection
and when you use the GetSection
method, you need to cast the return value as the type of your Custom class that you inherited off of System.Configuration.ConfigurationSection
see more here
An example would be if I had a special class to represent a property I wanted to store in either the App.Config or Web.Config such as:
public class MyConfig : ConfigurationSection
{
[ConfigurationProperty("myConfigProp", DefaultValue = "false", IsRequired = false)]
public Boolean MyConfigProp
{
get
{
return (Boolean)this["myConfigProp"];
}
set
{
this["myConfigProp"] = value;
}
}
}
Any time I would want to access that property I would do the following in my code:
//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;
There's some great samples on MSDN here: http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
Here, the "configuration type" is the custom type that's been created to extend ConfigurationSection
. Yes, this is implemented as an XML node, but the intent of the System.Configuration
namespace is to abstract this away.
精彩评论