.Net中的System.Configuration命名空间为我们在web.config或者app.config中自定义配置提供了完美的支持。
如果你已经对自定义配置了如指掌,请忽略这篇文章。
言归正传,我们先来看一个最简单的自定义配置
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
configuration
>
<
configSections
>
<
section
name
=
"simple"
type
=
"ConfigExample.Configuration.SimpleSection,ConfigExample"
/>
</
configSections
>
<
simple
maxValue
=
"20"
minValue
=
"1"
></
simple
>
</
configuration
>
|
在配置文件中使用自定义配置,需要在configSections中添加一个section元素,并制定此section元素对应的类型和名字。然后再在configuration根节点下面添加此自定义配置,如上例中的simple节点。simple节点只有两个整形数的属性maxValue和minValue。
要在程序中使用自定义配置我们还需要实现存取这个配置块的类型,一般需要做如下三件事:
1. 定义类型从System.Configuration.ConfigurationSection继承
2. 定义配置类的属性,这些属性需要用ConfigurationProperty特性修饰,并制定属性在配置节中的名称和其他一些限制信息
3. 通过基类的string索引器实现属性的get ,set
非常简单和自然,如下是上面配置类的实现:
public
class
SimpleSection:System.Configuration.ConfigurationSection
{
[ConfigurationProperty(
"maxValue"
,IsRequired=
false
,DefaultValue=Int32.MaxValue)]
public
int
MaxValue
{
get
{
return
(
int
)
base
[
"maxValue"
];
}
set
{
base
[
"maxValue"
] = value;
}
}
[ConfigurationProperty(
"minValue"
,IsRequired=
false
,DefaultValue=1)]
public
int
MinValue
{
get
{
return
(
int
)
base
[
"minValue"
];}
set
{
base
[
"minValue"
] = value; }
}
[ConfigurationProperty(
"enabled"
,IsRequired=
false
,DefaultValue=
true
)]
public
bool
Enable
{
get
{
return
(
bool
)
base
[
"enabled"
];
}
set
{
base
[
"enabled"
] = value;
}
}
}
|
这样子一个简单的配置类就完成了,怎么在程序中使用这个配置呢?需要使用ConfigurationManager类(要引用System.configuration.dll这个dll只有在.Net2.0之后的版本中才有)的GetSection方法获得配置就可以了。如下代码:
SimpleSection simple = ConfigurationManager.GetSection(
"simple"
)
as
SimpleSection;
Console.WriteLine(
"simple minValue={0} maxValue = {1}"
|