TypeInitializationException TypeInitializationException TypeInitializationException TypeInitializationException Class

定义

作为类初始值设定项引发的异常的包装器而引发的异常。The exception that is thrown as a wrapper around the exception thrown by the class initializer. 此类不能被继承。This class cannot be inherited.

public ref class TypeInitializationException sealed : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class TypeInitializationException : SystemException
type TypeInitializationException = class
    inherit SystemException
Public NotInheritable Class TypeInitializationException
Inherits SystemException
继承
TypeInitializationExceptionTypeInitializationExceptionTypeInitializationExceptionTypeInitializationException
属性

注解

当类初始值设定项初始化类型失败时,将创建一个 TypeInitializationException,并向其传递对由该类型的类初始值设定项引发的异常的引用。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. InnerException属性的TypeInitializationException保存着基础异常。The InnerException property of TypeInitializationException holds the underlying exception.

通常情况下,TypeInitializationException异常反映了灾难性条件 (运行时无法实例化一个类型),阻止应用程序继续执行。Typically, the TypeInitializationException exception reflects a catastrophic condition (the runtime is unable to instantiate a type) that prevents an application from continuing. 大多数情况下,TypeInitializationException引发响应应用程序的执行环境中的某些更改。Most commonly, the TypeInitializationException is thrown in response to some change in the executing environment of the application. 因此,而不可能进行故障排除调试代码中,异常应不以处理try / catch块。Consequently, other than possibly for troubleshooting debug code, the exception should not be handled in a try/catch block. 相反,应调查和消除异常的原因。Instead, the cause of the exception should be investigated and eliminated.

TypeInitializationException 使用 HRESULT COR_E_TYPEINITIALIZATION,其值 0x80131534。TypeInitializationException uses the HRESULT COR_E_TYPEINITIALIZATION, which has the value 0x80131534.

有关实例的初始属性值的列表TypeInitializationException,请参阅TypeInitializationException构造函数。For a list of initial property values for an instance of TypeInitializationException, see the TypeInitializationException constructors.

以下部分介绍一些情况下,TypeInitializationException引发异常。The following sections describe some of the situations in which a TypeInitializationException exception is thrown.

静态构造函数和 TypeInitializationExceptionStatic constructors and the TypeInitializationException

静态构造函数,如果存在,自动调用由运行时之前创建的一种类型的新实例。A static constructor, if one exists, is called automatically by the runtime before creating a new instance of a type. 开发人员可以显式定义静态构造函数。Static constructors can be explicitly defined by a developer. 如果未显式定义静态构造函数,编译器会自动创建一个用来初始化任何static(在 C# 中) 或Shared(在 Visual Basic) 类型的成员。If a static constructor is not explicitly defined, compilers automatically create one to initialize any static (in C#) or Shared (in Visual Basic) members of the type. 静态构造函数的详细信息,请参阅静态构造函数For more information on static constructors, see Static Constructors.

大多数情况下,TypeInitializationException当静态构造函数不能实例化一个类型时引发异常。Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type. InnerException属性指示为何无法实例化类型的静态构造函数。The InnerException property indicates why the static constructor was unable to instantiate the type. 一些更常见的原因TypeInitializationException异常是:Some of the more common causes of a TypeInitializationException exception are:

  • 静态构造函数中未经处理的异常An unhandled exception in a static constructor

    如果静态构造函数中引发异常,该异常包装在TypeInitializationException异常,并且该类型不能实例化。If an exception is thrown in a static constructor, that exception is wrapped in a TypeInitializationException exception, and the type cannot be instantiated.

    通常使此异常难以进行疑难解答的是静态构造函数没有始终显式定义在源代码中。What often makes this exception difficult to troubleshoot is that static constructors are not always explicitly defined in source code. 如果静态构造函数存在问题的一种类型:A static constructor exists in a type if:

    • 它已被显式定义为一种类型的成员。It has been explicitly defined as a member of a type.

    • 该类型具有static(在 C# 中) 或Shared(在 Visual Basic 中) 是声明并在单个语句中初始化的变量。The type has static (in C#) or Shared (in Visual Basic) variables that are declared and initialized in a single statement. 在这种情况下,语言编译器将生成类型的静态构造函数。In this case, the language compiler generates a static constructor for the type. 可以通过使用一个实用程序,如来检查IL 反汇编程序You can inspect it by using a utility such as IL Disassembler. 例如,当 C# 和 VB 编译器编译下面的示例,它们生成类似于以下的静态构造函数的 IL:For instance, when the C# and VB compilers compile the following example, they generate the IL for a static constructor that is similar to this:

    .method private specialname rtspecialname static   
            void  .cctor() cil managed  
    {  
      // Code size       12 (0xc)  
      .maxstack  8  
      IL_0000:  ldc.i4.3  
      IL_0001:  newobj     instance void TestClass::.ctor(int32)  
      IL_0006:  stsfld     class TestClass Example::test  
      IL_000b:  ret  
    } // end of method Example::.cctor  
    

    下面的示例演示TypeInitializationException由编译器生成的静态构造函数引发异常。The following example shows a TypeInitializationException exception thrown by a compiler-generated static constructor. Example类包括static(在 C# 中) 或Shared(在 Visual Basic) 字段类型的TestClass通过将值 3 传递给其类构造函数实例化。The Example class includes a static (in C#) or Shared (in Visual Basic) field of type TestClass that is instantiated by passing a value of 3 to its class constructor. 值,但是,是非法的;允许仅为 0 或 1 的值。That value, however, is illegal; only values of 0 or 1 are permitted. 因此,TestClass类构造函数将引发ArgumentOutOfRangeExceptionAs a result, the TestClass class constructor throws an ArgumentOutOfRangeException. 由于未处理此异常,它将包装在TypeInitializationException异常。Since this exception is not handled, it is wrapped in a TypeInitializationException exception.

    using System;
    
    public class Example
    {
       private static TestClass test = new TestClass(3);
       
       public static void Main()
       {
          Example ex = new Example();
          Console.WriteLine(test.Value);
       }
    }
    
    public class TestClass
    {
       public readonly int Value;
       
       public TestClass(int value)
       {
          if (value < 0 || value > 1) throw new ArgumentOutOfRangeException();
          Value = value;
       }
    }
    // The example displays the following output:
    //    Unhandled Exception: System.TypeInitializationException: 
    //       The type initializer for 'Example' threw an exception. ---> 
    //       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
    //       at TestClass..ctor(Int32 value)
    //       at Example..cctor()
    //       --- End of inner exception stack trace ---
    //       at Example.Main()
    
    Public Class Example
       Shared test As New TestClass(3)
       
       Public Shared Sub Main()
          Dim ex As New Example()
          Console.WriteLine(test.Value)
       End Sub
    End Class
    
    Public Class TestClass
       Public ReadOnly Value As Integer
       
       Public Sub New(value As Integer)
          If value < 0 Or value > 1 Then Throw New ArgumentOutOfRangeException()
          Value = value
       End Sub
    End Class
    ' The example displays the following output:
    '    Unhandled Exception: System.TypeInitializationException: 
    '       The type initializer for 'Example' threw an exception. ---> 
    '       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
    '       at TestClass..ctor(Int32 value)
    '       at Example..cctor()
    '       --- End of inner exception stack trace ---
    '       at Example.Main()
    

    请注意异常消息,显示有关的信息InnerException属性。Note that the exception message displays information about the InnerException property.

  • 缺少程序集或数据文件A missing assembly or data file

    一个常见原因TypeInitializationException例外情况是其运行时环境中缺少应用程序的开发和测试环境中已存在的程序集或数据文件。A common cause of a TypeInitializationException exception is that an assembly or data file that was present in an application's development and test environments is missing from its runtime environment. 例如,可以编译到程序集使用此命令行语法来命名 Missing1a.dll 下面的示例:For example, you can compile the following example to an assembly named Missing1a.dll by using this command-line syntax:

    csc -t:library Missing1a.cs  
    
    vbc Missing1a.vb -t:library  
    
    using System;
    
    public class InfoModule
    {
       private DateTime firstUse;
       private int ctr = 0;
    
       public InfoModule(DateTime dat)
       {
          firstUse = dat;
       }
       
       public int Increment()
       {
          return ++ctr;
       }
       
       public DateTime GetInitializationTime()
       {
          return firstUse;
       }
    }
    
    Public Class InfoModule
       Private firstUse As DateTime
       Private ctr As Integer = 0
    
       Public Sub New(dat As DateTime)
          firstUse = dat
       End Sub
       
       Public Function Increment() As Integer
          ctr += 1
          Return ctr
       End Function
       
       Public Function GetInitializationTime() As DateTime
          Return firstUse
       End Function
    End Class
    

    然后可以编译到可执行文件包括对 Missing1a.dll 的引用名为 Missing1.exe 下面的示例:You can then compile the following example to an executable named Missing1.exe by including a reference to Missing1a.dll:

    csc Missing1.cs /r:Missing1a.dll  
    
    vbc Missing1.vb /r:Missing1a.dll  
    

    但是,如果重命名、 移动或删除 Missing1a.dll 和运行示例,则会引发TypeInitializationException异常并显示在示例中所示的输出。However, if you rename, move, or delete Missing1a.dll and run the example, it throws a TypeInitializationException exception and displays the output shown in the example. 请注意,异常消息包含信息有关InnerException属性。Note that the exception message includes information about the InnerException property. 在这种情况下,内部异常是FileNotFoundException因为运行时找不到依赖程序集引发。In this case, the inner exception is a FileNotFoundException that is thrown because the runtime cannot find the dependent assembly.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person p = new Person("John", "Doe");
          Console.WriteLine(p);   
       }
    }
    
    public class Person
    {
       static InfoModule infoModule;
       
       String fName;
       String mName;
       String lName;
       
       static Person()
       {
          infoModule = new InfoModule(DateTime.UtcNow);
       }
       
       public Person(String fName, String lName)
       {
          this.fName = fName;
          this.lName = lName;
          infoModule.Increment();
       }
       
       public override String ToString()
       {
          return String.Format("{0} {1}", fName, lName);
       }
    }
    // The example displays the following output if missing1a.dll is renamed or removed:
    //    Unhandled Exception: System.TypeInitializationException: 
    //       The type initializer for 'Person' threw an exception. ---> 
    //       System.IO.FileNotFoundException: Could not load file or assembly 
    //       'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
    //       or one of its dependencies. The system cannot find the file specified.
    //       at Person..cctor()
    //       --- End of inner exception stack trace ---
    //       at Person..ctor(String fName, String lName)
    //       at Example.Main()
    
    Module Example
       Public Sub Main()
          Dim p As New Person("John", "Doe")
          Console.WriteLine(p)   
       End Sub
    End Module
    
    Public Class Person
       Shared infoModule As InfoModule
       
       Dim fName As String
       Dim mName As String
       Dim lName As String
       
       Shared Sub New()
          infoModule = New InfoModule(DateTime.UtcNow)
       End Sub
       
       Public Sub New(fName As String, lName As String)
          Me.fName = fName
          Me.lName = lName
          infoModule.Increment()
       End Sub
       
       Public Overrides Function ToString() As String
          Return String.Format("{0} {1}", fName, lName)
       End Function
    End Class
    ' The example displays the following output if missing1a.dll is renamed or removed:
    '    Unhandled Exception: System.TypeInitializationException: 
    '       The type initializer for 'Person' threw an exception. ---> 
    '       System.IO.FileNotFoundException: Could not load file or assembly 
    '       'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
    '       or one of its dependencies. The system cannot find the file specified.
    '       at Person..cctor()
    '       --- End of inner exception stack trace ---
    '       at Person..ctor(String fName, String lName)
    '       at Example.Main()
    

    备注

    在此示例中,TypeInitializationException已引发异常,因为无法加载程序集。In this example, a TypeInitializationException exception was thrown because an assembly could not be loaded. 如果静态构造函数尝试打开数据文件,如配置文件、 XML 文件,或一个文件,其中包含序列化: 找不到的数据,也可以引发异常。The exception can also be thrown if a static constructor attempts to open a data file, such as a configuration file, an XML file, or a file containing serialized data, that it cannot find.

正则表达式匹配超时值Regular expression match timeout values

可以设置正则表达式模式匹配的每个应用程序域基础上操作的默认超时值。You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. 通过指定定义超时TimeSpan到"REGEX_DEFAULT_MATCH_TIMEOUT"属性值为AppDomain.SetData方法。The timeout is defined by a specifying a TimeSpan value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the AppDomain.SetData method. 必须是有效的时间间隔TimeSpan对象,它是大于零且小于大约 24 天。The time interval must be a valid TimeSpan object that is greater than zero and less than approximately 24 days. 如果不满足这些要求,尝试设置的默认超时值将引发ArgumentOutOfRangeException,这又包装在TypeInitializationException异常。If these requirements are not met, the attempt to set the default timeout value throws an ArgumentOutOfRangeException, which in turn is wrapped in a TypeInitializationException exception.

下面的示例演示TypeInitializationException分配给"REGEX_DEFAULT_MATCH_TIMEOUT"属性的值无效时引发。The following example shows the TypeInitializationException that is thrown when the value assigned to the "REGEX_DEFAULT_MATCH_TIMEOUT" property is invalid. 若要消除此异常,请将"REGEX_DEFAULT_MATCH_TIMEOUT"属性设置为TimeSpan大于零且小于大约 24 天的值。To eliminate the exception, set the"REGEX_DEFAULT_MATCH_TIMEOUT" property to a TimeSpan value that is greater than zero and less than approximately 24 days.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      AppDomain domain = AppDomain.CurrentDomain;
      // Set a timeout interval of -2 seconds.
      domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2));

      Regex rgx = new Regex("[aeiouy]");
      Console.WriteLine("Regular expression pattern: {0}", rgx.ToString());
      Console.WriteLine("Timeout interval for this regex: {0} seconds",
                        rgx.MatchTimeout.TotalSeconds);
   }
}
// The example displays the following output:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> 
//       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
//       Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or 
//       object for specifying a default matching timeout for System.Text.RegularExpressions.Regex.
//       at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout()
//       at System.Text.RegularExpressions.Regex..cctor()
//       --- End of inner exception stack trace ---
//       at System.Text.RegularExpressions.Regex..ctor(String pattern)
//       at Example.Main()
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim domain As AppDomain = AppDomain.CurrentDomain
      ' Set a timeout interval of -2 seconds.
      domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2))

      Dim rgx As New Regex("[aeiouy]")
      Console.WriteLine("Regular expression pattern: {0}", rgx.ToString())
      Console.WriteLine("Timeout interval for this regex: {0} seconds",
                        rgx.MatchTimeout.TotalSeconds)
   End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.TypeInitializationException: 
'       The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> 
'       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
'       Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or 
'       object for specifying a default matching timeout for System.Text.RegularExpressions.Regex.
'       at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout()
'       at System.Text.RegularExpressions.Regex..cctor()
'       --- End of inner exception stack trace ---
'       at System.Text.RegularExpressions.Regex..ctor(String pattern)
'       at Example.Main()

日历和区域性的数据Calendars and cultural data

如果尝试实例化一个日历,但运行时无法实例化CultureInfo对象,它对应于该日历,则会引发TypeInitializationException异常。If you attempt to instantiate a calendar but the runtime is unable to instantiate the CultureInfo object that corresponds to that calendar, it throws a TypeInitializationException exception. 可以通过以下日历类构造函数引发此异常:This exception can be thrown by the following calendar class constructors:

由于这些区域性的区域性数据应是适用于所有系统,您应该很少,如果有过,遇到此异常。Since cultural data for these cultures should be available on all systems, you should rarely, if ever, encounter this exception.

构造函数

TypeInitializationException(String, Exception) TypeInitializationException(String, Exception) TypeInitializationException(String, Exception) TypeInitializationException(String, Exception)

用默认错误消息、指定的类型名称和对内部异常(为该异常的根源)的引用来初始化 TypeInitializationException 类的新实例。Initializes a new instance of the TypeInitializationException class with the default error message, the specified type name, and a reference to the inner exception that is the root cause of this exception.

属性

Data Data Data Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

获取描述当前异常的消息。Gets a message that describes the current exception.

(Inherited from Exception)
Source Source Source Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(Inherited from Exception)
TypeName TypeName TypeName TypeName

获取未能初始化类型的完全限定名。Gets the fully qualified name of the type that fails to initialize.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

设置带有文件名和附加异常信息的 SerializationInfo 对象。Sets the SerializationInfo object with the type name and additional exception information.

GetType() GetType() GetType() GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception.

(Inherited from Exception)

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

适用于

另请参阅