C#中的TypeInitializationException [英] TypeInitializationException in C#

查看:387
本文介绍了C#中的TypeInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将基于教程创建一个学生信息系统。
一旦用户想要向数据库中添加新学生,就会发生以下异常。



我试图学习有关TypeInitializationException的一些知识,但我对它的名字有所了解。.但是我无法完全理解它。此外,我正在关注的教程中没有例外。.我是这种OOP编程和处理错误的新手。我在下面包括了数据库连接和数据库访问类。





我的 DB_Connection

 使用System.Linq; 
使用System.Text;
使用System.Threading.Tasks;
使用System.Data;
使用System.Data.SqlClient;
使用System.Configuration;

名称空间studentInformationSystem
{
类DB_Connection
{
public static SqlConnection NewConnection;
公共静态字符串ConString = ConfigurationManager.ConnectionStrings [ ConString]。ConnectionString;

公共静态SqlConnection getConnection()
{
NewConnection = new SqlConnection(ConString);
返回NewConnection;
}
}
}

我的 DB_Access

 使用系统; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;
使用System.Data;
使用System.Data.SqlClient;

名称空间studentInformationSystem
{
类DB_Access
{
public SqlConnection conn;
public DB_Access()
{
conn = DB_Connection.getConnection();
}

public void AddStudent(字符串regNo,字符串fName,字符串lName,字符串phoneNumber)
{
if(conn.State.ToString()==已关闭)
{
conn.Open();
}

SqlCommand newCommand = conn.CreateCommand();
newCommand.Connection = conn; //为什么要使用它。
newCommand.CommandType = CommandType.Text;
newCommand.CommandText =插入学生值(’ + regNo +’,’ + fName +’,’ + lName +’,’ + phoneNumber +’);
newCommand.ExecuteNonQuery();

}
}
}

我的connectionString

 <?xml version = 1.0 encoding = utf-8吗? 
< configuration>
< startup>
< supportedRuntime版本= v4.0 sku =。NETFramework,Version = v4.5 />
< / startup>

< configSections>

< connectionStrings>
< add name = ConString connectionString = Data Source = SADID-PC\SQLEXPRESS; Initial Catalog = Test1; Integrated Security = True
providerName = System.Data.sqlClient /> ;
< / connectionStrings>

< / configSections>

< / configuration>


解决方案

在您的情况下:



这意味着以下行失败:

 公共静态字符串ConString = 
ConfigurationManager.ConnectionStrings [ ConString]。ConnectionString;

请确保此处没有异常!由于此行是作为 DB_Connection 类型初始化的一部分执行的,因此当您首次访问 DB_Connection 时会发生异常。发生在 DB_Connection.getConnection()中-因为您没有 DB_Connection 的其他(关键)初始化逻辑,所以基本上<



我强烈建议移动逻辑,例如将 ConString 初始化为a方法(类似于 Init 之类的方法),因此您将可以更好地控制所发生的事情-调试起来也更加容易!



从那里开始,我猜 ConnectionStrings [ ConString] 返回 null 或抛出一个异常本身,但是您会发现那很容易。 ;)



更一般的描述,适用于遇到相似问题的人:



每当抛出 TypeInitializationException 时,请在语句中第一次检查所引用类型的 all 初始化逻辑,其中



初始化逻辑包括:类型的静态构造函数和(在这种情况下)字段初始化。



如果此时您仍然不知道实际的异常发生在哪里(然后触发 TypeInitializationException ),则应考虑将所有移动(或初始化逻辑的一部分)。现在,当您手动调用此方法时(当然,在您首次访问该类型之前),您可以从IDE的调试功能中受益,并且最重要的是,将抛出 actual 异常。 p>

I'm going to create a student information system based on a tutorial. As soon as a user wants to add a new student to the database the following exception occurs.

I tried to learn something about TypeInitializationException and I understand a little by its name.. but I can't get it totally. Besides, the exception is absent from the tutorial I'm following.. I'm new in this type of OOP programming and handling errors. I included my database connection and database access class below..

My DB_Connection class

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace studentInformationSystem
{
    class DB_Connection
    {
        public static SqlConnection NewConnection;
        public static string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

        public static SqlConnection getConnection()
        {
            NewConnection = new SqlConnection(ConString);
            return NewConnection;
        }
    }
}

My DB_Access class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace studentInformationSystem
{
    class DB_Access
    {
        public SqlConnection conn;
        public DB_Access()
        {
            conn = DB_Connection.getConnection();
        }

        public void AddStudent(string regNo, string fName, string lName, string phoneNumber)
        {
            if(conn.State.ToString() == "Closed")
            {
                conn.Open();
            }

            SqlCommand newCommand = conn.CreateCommand();
            newCommand.Connection = conn; //why we use it..???
            newCommand.CommandType = CommandType.Text;
            newCommand.CommandText = "insert into student values('" + regNo + "','" + fName + "','" + lName + "','" + phoneNumber + "')";
            newCommand.ExecuteNonQuery();

        }
    }
}

here is my connectionString

  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

  <configSections>

    <connectionStrings>
      <add name="ConString" connectionString="Data Source=SADID-PC\SQLEXPRESS;Initial Catalog=Test1;Integrated Security=True" 
           providerName="System.Data.sqlClient" />  
    </connectionStrings>

  </configSections>

</configuration>

解决方案

In your case:

This means that the following line fails:

public static string ConString = 
    ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

Make sure that no exception happens here! Since this line is executed as part of DB_Connection's type initialization, the exception occurs when you first access DB_Connection, which happens at DB_Connection.getConnection() - since you have no other (critical) initialization logic for DB_Connection, it basically has to be that line.

I strongly recommend moving logic like initializing ConString to a method (something like Init), so you will have more control about what happens - and much easier debugging!

Going from there, I guess ConnectionStrings["ConString"] returns null or throws an exception itself - but you will find that out easily. ;)

More general description, for people having similar problems:

Whenever TypeInitializationException is thrown, check all initialization logic of the type you are referring to for the first time in the statement where the exception is thrown.

Initialization logic includes: the type's static constructor and (like in this case) field initialization.

If at this point you still have no idea where the actual exception (that then triggers TypeInitializationException) happens, you should consider moving all (or parts of your) initialization logic to an extra static method. When you now call this method manually (before you first access the type, of course) you can benefit from your IDEs debugging abilities and will, most importantly, get the actual exception thrown at your head.

这篇关于C#中的TypeInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆