简体   繁体   English

意外的异常:System.TypeInitializationException

[英]Unexpected Exceptions: System.TypeInitializationException

using c#, .Net Framework 4.5 使用C#、. Net Framework 4.5

Try to crete simple programm with next code: 尝试使用下一个代码创建简单的程序:

 enum DataProvider { Sqlserver, Obdc, Oledb, None }

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("simple database connection factory");
        IDbConnection Idbc = GetConnection(DataProvider.Sqlserver);
        Console.WriteLine("your connection - {0}", Idbc.GetType().Name);
        Console.ReadLine();
    }
    private static IDbConnection GetConnection(DataProvider dataProvider)
    {
        IDbConnection connection = null;
        switch (dataProvider)
        {
            case DataProvider.Sqlserver:
                connection = new SqlConnection();
                break;
            case DataProvider.Oledb:
                connection = new OleDbConnection();
                break;
            case DataProvider.Obdc :
                connection = new OdbcConnection();
                break;
        }
        return connection;
    }
}

First time it's run ok - gor required result, but now get Exceptions: System.TypeInitializationException on string connection = new SqlConnection(); 第一次运行正常-gor要求的结果,但是现在出现Exceptions: System.TypeInitializationException字符串connection = new SqlConnection();上的Exceptions: System.TypeInitializationException connection = new SqlConnection(); .

See help in MSDN but can find only When a class initializer fails to initialize a type, a TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer But whats is reason for fail to initialize a type? 请参见MSDN中的帮助,但只能找到它。 When a class initializer fails to initialize a type, a TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer但是,为什么无法初始化类型呢? why first time it's runned ok and second time i got error? 为什么第一次运行正常,第二次出现错误?

As mentioned by Ahmet Kakıcı - check inner exception - like sown on pic below 正如AhmetKakıcı提到的那样 -检查内部异常-如下图所示

内在异常的

found, a lot of innered exception and the last one was with description {System.Configuration.ConfigurationException[1]} 发现了很多内在的异常,最后一个是描述{System.Configuration.ConfigurationException[1]}

Try just reset MyApp.exe.config file (put default values like below : 尝试仅重置MyApp.exe.config文件(输入如下默认值:

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

As result - now all it's ok. 结果-现在一切正常。

Real reason whats happend with .config file - really don't know... 真正的原因.config文件发生了什么-真的不知道...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM