配置类的使用,可以很方便把程序中需要经常变化常量从配置文件中读取,很多时候,我们要把文件路径,数据库地址,我们程序设置的各种环境变量放到一个配置文件中,使我们程序在使用过程中灵活读取。虽然WEB程序中我们可以把需要的配置节放到webconfig文件中,而且有现成读取方法,可当我们需要大量设置时,显然webconfig不是一个明智的选择,这时就需要我们手动定义一些配置文件,当然我们也需要自定义配置类。
首先配置文件,我们需要的是一个XML文件,因为.net中有很多读取XML文件方式,手工写起来还有好多工具可用,而且也符合我们的使用习惯。看以下配置文件
2 < Settings >
3 < TopMenu id ="User" name ="用户昵称" title ="用户昵称" >
4 < LeftMenu id ="EditProfile" name ="基本信息" title ="基本信息" url ="/Users/Manages/baseinfo.aspx" >
5 </ LeftMenu >
6 < LeftMenu id ="EditCharacter" name ="详细信息" title ="详细信息" url ="/Users/Manages/Editinfo.aspx" >
7 </ LeftMenu >
8 </ TopMenu >
9 </ Settings >
我们的配置类,需要的一个静态类,最好是sealed,因为我们不需要它继承。我们可以随时读取信息,XML的读取,如果再细的话,我们可以把读取XML信息缓冲起来,不用频繁从外设读取文件,节省时间,如果配置文件发生变化呢,我们当然可以在缓冲时从文件依赖,一个小小的配置类详细设计时,里面包含不少设计模式。
{
#region Member variables & constructor
private static Settings instance = null ;
Dictionary < string , string > settings = null ;
public Settings(XmlDocument doc)
{
settings = new Dictionary < string , string > (StringComparer.InvariantCultureIgnoreCase);
XmlNode root = doc.SelectSingleNode( " Settings " );
foreach (XmlNode n in root.ChildNodes)
{
if (n.NodeType != XmlNodeType.Comment)
{
string name = n.Attributes[ " name " ].Value.ToLower();
string setting = n.Attributes[ " value " ].Value;
if ( ! settings.ContainsKey(name))
{
settings.Add(name, setting);
}
}
}
}
#endregion
#region GetConfig
public static Settings GetConfig()
{
if (instance == null )
{
string file = null ;
Configurations config = Configurations.GetConfig();
string configFile = config.SettingsConfigPath;
HttpContext context = HttpContext.Current;
if (context != null )
file = context.Server.MapPath( " ~/ " + configFile);
XmlDocument doc = new XmlDocument();
doc.Load(file);
instance = new Settings(doc);
}
return instance;
}
#endregion
#region Public properties
public string GetSetting( string key)
{
if (settings.ContainsKey(key))
{
return settings[key];
}
return string .Empty;
}
#endregion
}
以上代码的可扩展如果我们增加一些重载方法,因为我们读取不全是string 可能是bool 或其它的,我们如果多个不同 配置文件,而且作用不用,我们需要一个大的局配置类把这些配置类再次包装起来,读时分门别类使用方便,配置类简单,可不简约。