TypeInitializationException 类
定义
作为类初始值设定项引发的异常的包装器而引发的异常。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 : Exception
public ref class TypeInitializationException sealed : SystemException
public sealed class TypeInitializationException : Exception
public sealed class TypeInitializationException : SystemException
[System.Serializable]
public sealed class TypeInitializationException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TypeInitializationException : SystemException
type TypeInitializationException = class
inherit Exception
type TypeInitializationException = class
inherit SystemException
[<System.Serializable>]
type TypeInitializationException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TypeInitializationException = class
inherit SystemException
Public NotInheritable Class TypeInitializationException
Inherits Exception
Public NotInheritable Class TypeInitializationException
Inherits SystemException
- 继承
- 继承
- 属性
注解
当类初始值设定项初始化类型失败时,将创建一个 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.
- 静态构造函数和 System.typeinitializationexception 异常Static constructors and the TypeInitializationException exception
- 正则表达式匹配超时值Regular expression match timeout values
- 日历和文化数据Calendars and cultural data
静态构造函数和 System.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.
该类型在
staticc # 中具有 () 或Shared(Visual Basic) 在单个语句中声明和初始化的变量。The type hasstatic(in C#) orShared(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类包含staticc # 中的一个 () 或Shared(在TestClass通过将值3传递到其类构造函数而实例化的类型 Visual Basic) 字段中。TheExampleclass includes astatic(in C#) orShared(in Visual Basic) field of typeTestClassthat 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类构造函数会引发 ArgumentOutOfRangeException 。As a result, theTestClassclass 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.csvbc Missing1a.vb -t:libraryusing 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.dllvbc 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. 以下 calendar 类构造函数可能会引发此异常:This exception can be thrown by the following calendar class constructors:
类的无参数构造函数 JapaneseCalendar 。The parameterless constructor of the JapaneseCalendar class.
类的无参数构造函数 KoreanCalendar 。The parameterless constructor of the KoreanCalendar class.
类的无参数构造函数 TaiwanCalendar 。The parameterless constructor of the TaiwanCalendar class.
由于这些区域性的区域性数据应在所有系统上都可用,因此,您几乎不会遇到此异常。Since cultural data for these cultures should be available on all systems, you should rarely, if ever, encounter this 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 |
获取键/值对的集合,这些键/值对提供有关该异常的其他用户定义信息。Gets a collection of key/value pairs that provide additional user-defined information about the exception. (继承自 Exception) |
| HelpLink |
获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception. (继承自 Exception) |
| HResult |
获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (继承自 Exception) |
| InnerException |
获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception. (继承自 Exception) |
| Message |
获取描述当前异常的消息。Gets a message that describes the current exception. (继承自 Exception) |
| Source |
获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error. (继承自 Exception) |
| StackTrace |
获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack. (继承自 Exception) |
| TargetSite |
获取引发当前异常的方法。Gets the method that throws the current exception. (继承自 Exception) |
| TypeName |
获取未能初始化类型的完全限定名。Gets the fully qualified name of the type that fails to initialize. |
方法
| Equals(Object) |
确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object. (继承自 Object) |
| GetBaseException() |
当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根本原因。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (继承自 Exception) |
| GetHashCode() |
作为默认哈希函数。Serves as the default hash function. (继承自 Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
设置带有文件名和附加异常信息的 SerializationInfo 对象。Sets the SerializationInfo object with the type name and additional exception information. |
| GetObjectData(SerializationInfo, StreamingContext) |
当在派生类中重写时,用关于异常的信息设置 SerializationInfo。When overridden in a derived class, sets the SerializationInfo with information about the exception. (继承自 Exception) |
| GetType() |
获取当前实例的运行时类型。Gets the runtime type of the current instance. (继承自 Exception) |
| MemberwiseClone() |
创建当前 Object 的浅表副本。Creates a shallow copy of the current Object. (继承自 Object) |
| ToString() |
创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception. (继承自 Exception) |
事件
| SerializeObjectState |
当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (继承自 Exception) |