TypeInitializationException例外创建一个对象创建一个、对象、TypeInitializationException

2023-09-04 22:55:40 作者:梅川库子i

我有一个程序集(在.NET 3.5中类库项目),有像 System.Configuration 的System.Web 。我用它的Web应用程序,它工作正常。

I have an assembly (class library project in .Net 3.5) that has some references like System.Configuration and System.Web. I use it on a web application and it works fine.

现在,我需要做一个参考到Windows窗体项目,我不明白发生了什么。当我尝试创建我的课也不能正常工作的一个实例;异常类型的 TypeInitializationException 被抛出。

Now, I need to make a reference to a Windows Forms project and I can't understand what is happening. When I try to create an instance of my class it does not work; an exception of type TypeInitializationException is thrown.

我尝试创建我的组装和那些工作的其他情况,但这个特定的类。

I try to create other instances of my assembly and those work, except this specific class.

有谁知道发生了什么事?

Does anybody know what is happening?

推荐答案

TypeInitializationException通常是抛出当类的静态字段不能被初始化。例如:

TypeInitializationException is usually thrown when a static field of the class can't be initialized. For example:

class BadClass
{
    private static MyClass fieldName = new MyClass();
}

会造成前BadClass的第一次使用一个TypeInitializationException如果构造MyClass的抛出。

Will cause a TypeInitializationException prior to the first usage of BadClass if the constructor for MyClass throws.

您可以看看TypeInitializationException深入到了失败的原因进行更详细的InnerException属性。它通常将指向您导致类型初始化失败底层例外。

You can look at the InnerException property of the TypeInitializationException to drill down into the cause of the failure in more detail. It will usually point you to the underlying exception that caused the type initialization to fail.