TypeInitializationException 類別

定義

因為當做類別初始設定式 (Class Initializer) 所擲回例外狀況的包裝函式,所擲回的例外狀況。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
繼承
TypeInitializationException
屬性

備註

當類別初始設定式無法初始化型別時,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. InnerExceptionTypeInitializationException屬性會保存基礎例外狀況。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. 因此, 除了可能針對 debug 程式碼進行疑難排解以外, 不應在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.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. C# Shared類別包含型別TestClass的 (在中) 或 (在 Visual Basic) 欄位, 其會透過將值3傳遞給其類別的函式來具現化。 static ExampleThe 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 「函式ArgumentOutOfRangeException」會擲回。As 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 的元件: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 的參考, 將下列範例編譯為名為 Missing1 的可執行檔: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, 並執行範例, 它會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. 此超時時間是由將 "REGEX_DEFAULT_MATCH_TIMEOUT TimeSpan " 屬性的值指定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 類別的新執行個體。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()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen 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)

以型別名稱和其他例外狀況 (Exception) 資訊設定 SerializationInfo 物件。Sets the SerializationInfo object with the type name and additional exception information.

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)

適用於

另請參閱