您的位置:首页 > 其它

TypeInitilizationException的解决办法

2008-12-18 08:18 183 查看
准备写一个静态类Config,这个类有静态成员ConnectionString,准备用来读取配置文件中的加密的数据库连接字符串。静态成员当然在静态构造函数中初始化,于是这样写:
public class Config
{
// 数学试题库的数据库连接字符串
private static string _mathDbConnectionString = null;
public static string MathDbConnectionString
{
get
{
return _mathDbConnectionString;
}
}
static Config()
{
// Db.Config是程序中使用的运行目录下的配置文件,Db.Config.Config是实际的配置文件
string configFile = Application.StartupPath + @"/DB.Config";
string configRealFile = Application.StartupPath + @"/DB.Config.Config";

// 配置文件不存在,抛出“文件不存在”的异常
if (!File.Exists(configFile) || !File.Exists(configRealFile))
{
thorw new System.IO.FileNotFoundException("配置文件不存在。");
}

// 读取Db.Config文件中的数据库连接字符串
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration

(Application.StartupPath + @"/DB.Config");
_mathDbConnectionString = config.ConnectionStrings.ConnectionStrings

["MathConnStr"].ConnectionString;
}
catch (Exception ex) // 如果有异常发生,说明配置文件格式错
{
throw ex;
}
}
结果,在Db.Config文件能够正常读取的时候没有问题。当Db.Config文件不存在的时候,获取MathDbConnnectionString属性值时总是出现:TypeInitializationException异常,类型初始值设定项引发异常。
很是郁闷,为什么获取的不是FileNotFoundException异常呢?这样的代码(在有问题时抛出异常)是没有问题的呀?
最终在“IT设计者之家”上找到这样一篇文章:类型初始值设定项引发异常原因及解决方法(http://www.it55.com/html/xueyuan/chengxukaifa/_NETjiaocheng/20071123/261484.html),其中提到:原来类的静态成员在初始化时如果出现异常,访问类的其它静态成员或对该类进行初始化都会抛出这个异常。如果类中存在静态成员,应确保其初始化时不会抛出异常,否则会影响对该类的正常访问。
于是,将上面的静态构造函数改成如下:
static Config()
{
// Db.Config是程序中使用的运行目录下的配置文件,Db.Config.Config是实际的配置文件
string configFile = Application.StartupPath + @"/DB.Config";
string configRealFile = Application.StartupPath + @"/DB.Config.Config";

// 配置文件不存在,设置连接字符串和连接对象为空值
if (!File.Exists(configFile) || !File.Exists(configRealFile))
{
_mathDbConnectionString = null;
_mathDbConnection = null;
return;
}

// 读取Db.Config文件中的数据库连接字符串
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.StartupPath + @"/DB.Config");
_mathDbConnectionString = config.ConnectionStrings.ConnectionStrings["MathConnStr"].ConnectionString;
}
catch // 如果有异常发生,说明配置文件格式错
{
_mathDbConnectionString = null;
_mathDbConnection = null;
return;
}
这样,如果获取的MathDbConnectionString值是null,就可以说明没有正确读取到数据库连接字符串了。

2008年12月18日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐