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 : 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
繼承
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. 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 / catchConsequently, 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.

下列各節說明擲回例外狀況的部分情況 TypeInitializationExceptionThe 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. 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. 因為不會處理此例外狀況,所以會將它包裝在例外狀況中 TypeInitializationExceptionSince 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()
    

    請注意,例外狀況訊息會顯示內容的相關資訊 InnerExceptionNote 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. 請注意,例外狀況訊息包含屬性的相關資訊 InnerExceptionNote that the exception message includes information about the InnerException property. 在此情況下,內部例外狀況是因為執行時間找不到相依元件而擲回的 FileNotFoundExceptionIn 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. Timeout 的定義方式是指定方法的 TimeSpan "REGEX_DEFAULT_MATCH_TIMEOUT" 屬性值 AppDomain.SetDataThe 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 ,而這會在例外狀況中包裝 TypeInitializationExceptionIf 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.

GetObjectData(SerializationInfo, StreamingContext)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfoWhen 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)

適用於

另請參閱