System.TypeInitializationException sınıfı

Bu makale, bu API'nin başvuru belgelerine ek açıklamalar sağlar.

Sınıf başlatıcı bir türü başlatamadığında, bir TypeInitializationException oluşturulur ve türün sınıf başlatıcısı tarafından oluşturulan özel duruma bir başvuru geçirilir. InnerException özelliğiTypeInitializationException, temel alınan özel durumu tutar.

Genellikle, TypeInitializationException özel durum bir uygulamanın devam etmesini engelleyen bir yıkıcı koşulu yansıtır (çalışma zamanı bir tür örneği oluşturamaz). En yaygın olarak, TypeInitializationException uygulamanın yürütme ortamındaki bazı değişikliklere yanıt olarak oluşturulur. Sonuç olarak, hata ayıklama kodu sorunlarını gidermek için büyük olasılıkla dışında, özel durum bir try/catch blokta işlenmemelidir. Bunun yerine, özel durumun nedeni araştırılmalı ve ortadan kaldırılmalıdır.

TypeInitializationException , 0x80131534 değerine sahip HRESULT COR_E_TYPEINITIALIZATIONkullanır.

örneğinin ilk özellik değerlerinin TypeInitializationExceptionlistesi için oluşturuculara TypeInitializationException bakın.

Aşağıdaki bölümlerde özel durumun oluştuğu bazı durumlar TypeInitializationException açıklanmaktadır.

Statik oluşturucular

Varsa, bir statik oluşturucu, türün yeni bir örneğini oluşturmadan önce çalışma zamanı tarafından otomatik olarak çağrılır. Statik oluşturucular bir geliştirici tarafından açıkça tanımlanabilir. Statik oluşturucu açıkça tanımlanmamışsa, derleyiciler türün herhangi bir static (C# veya F# dilinde) veya Shared (Visual Basic'te) üyelerini başlatmak için otomatik olarak bir tane oluşturur. Statik oluşturucular hakkında daha fazla bilgi için bkz . Statik Oluşturucular.

En yaygın olarak, statik bir TypeInitializationException oluşturucu bir tür örneği oluşturamadığında bir özel durum oluşturulur. özelliği, InnerException statik oluşturucunun türün örneğini neden oluşturamadığını gösterir. Bir özel durumun daha yaygın nedenlerinden TypeInitializationException bazıları şunlardır:

  • Statik oluşturucuda işlenmeyen özel durum

    Statik bir oluşturucuda özel durum oluşturulursa, bu özel durum bir TypeInitializationException özel duruma sarmalanır ve tür örneği oluşturulamaz.

    Bu özel durumun sorun gidermesini sık sık zorlaştıran şey, statik oluşturucuların her zaman kaynak kodunda açıkça tanımlanmamasıdır. Aşağıdaki durumlarda bir tür içinde statik bir oluşturucu bulunur:

    • Bir türün üyesi olarak açıkça tanımlanmıştır.

    • Türün tek bir deyimde bildirilen ve başlatılan (C# veya F#'da) veya Shared (Visual Basic'te) değişkenleri vardır static . Bu durumda, dil derleyicisi türü için statik bir oluşturucu oluşturur. IL Disassembler gibi bir yardımcı program kullanarak bunu inceleyebilirsiniz. Örneğin, C# ve VB derleyicileri aşağıdaki örneği derlediğinde, buna benzer bir statik oluşturucu için IL oluşturur:

    .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
    

    Aşağıdaki örnekte, derleyici tarafından oluşturulan statik oluşturucu tarafından oluşturulan bir özel durum gösterilmektedir TypeInitializationException . sınıfı, Example sınıf oluşturucusunun 3 değerini geçirerek örneği oluşturulan türünde TestClass bir (C#'ta) veya Shared (Visual Basic'te) alanı içerir static . Ancak bu değer yasa dışıdır; yalnızca 0 veya 1 değerlerine izin verilir. Sonuç olarak, TestClass sınıf oluşturucu bir ArgumentOutOfRangeExceptionoluşturur. Bu özel durum işlenmediğinden, bir TypeInitializationException özel duruma sarmalanır.

    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(nameof(value));
          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 Example1
        Shared test As New TestClass(3)
    
        Public Shared Sub Main()
            Dim ex As New Example1()
            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(NameOf(value))
            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()
    

    Özel durum iletisinin özelliğiyle ilgili bilgileri görüntülediğine InnerException dikkat edin.

  • Eksik bir derleme veya veri dosyası

    Bir özel durumun yaygın bir TypeInitializationException nedeni, uygulamanın geliştirme ve test ortamlarında bulunan bir derleme veya veri dosyasının çalışma zamanı ortamında eksik olmasıdır. Örneğin, bu komut satırı söz dizimini kullanarak aşağıdaki örneği Missing1a.dll adlı bir derlemeye derleyebilirsiniz:

    csc -t:library Missing1a.cs
    
    fsc --target:library Missing1a.fs
    
    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;
       }
    }
    
    open System
    
    type InfoModule(firstUse: DateTime) =
        let mutable ctr = 0
    
        member _.Increment() =
            ctr <- ctr + 1
            ctr
       
        member _.GetInitializationTime() =
            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
    

    Ardından, Missing1a.dll başvurusu ekleyerek aşağıdaki örneği Missing1.exe adlı bir yürütülebilir dosyaya derleyebilirsiniz:

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

    Ancak, Missing1a.dll yeniden adlandırır, taşır veya siler ve örneği çalıştırırsanız, bir TypeInitializationException özel durum oluşturur ve örnekte gösterilen çıkışı görüntüler. Özel durum iletisinin özelliği hakkında bilgi içerdiğini InnerException unutmayın. Bu durumda, iç özel durum, çalışma zamanı bağımlı derlemeyi bulamadığından oluşan bir FileNotFoundException özel durumdur.

    using System;
    
    public class MissingEx1
    {
        public static void Main()
        {
            Person p = new Person("John", "Doe");
            Console.WriteLine(p);
        }
    }
    
    public class Person
    {
        static readonly InfoModule s_infoModule;
    
        readonly string _fName;
        readonly string _lName;
    
        static Person()
        {
            s_infoModule = new InfoModule(DateTime.UtcNow);
        }
    
        public Person(string fName, string lName)
        {
            _fName = fName;
            _lName = lName;
            s_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()
    
    open System
    
    type Person(fName, lName) =
        static let infoModule = InfoModule DateTime.UtcNow
        
        do infoModule.Increment() |> ignore
       
        override _.ToString() =
            $"{fName} {lName}"
    let p = Person("John", "Doe")
    
    printfn $"{p}"
    // 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 Example3
        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()
    

    Not

    Bu örnekte, bir TypeInitializationException derleme yüklenemediği için bir özel durum oluşturuldu. Statik bir oluşturucu, yapılandırma dosyası, XML dosyası veya serileştirilmiş veri içeren bir dosya gibi bir veri dosyasını açmaya çalışırsa ve bu dosyayı bulamazsa, özel durum oluşturulabilir.

Normal ifade zaman aşımı değerlerini eşleştir

Normal ifade deseni eşleştirme işlemi için varsayılan zaman aşımı değerini uygulama başına etki alanı temelinde ayarlayabilirsiniz. Zaman aşımı, yöntemine "REGEX_DEFAULT_MATCH_TIMEOUT" özelliği AppDomain.SetData için bir TimeSpan değer belirtilerek tanımlanır. Zaman aralığı, sıfırdan büyük ve yaklaşık 24 günden kısa geçerli TimeSpan bir nesne olmalıdır. Bu gereksinimler karşılanmazsa, varsayılan zaman aşımı değerini ayarlama girişimi, ArgumentOutOfRangeExceptionbir özel durumda sarmalanan bir TypeInitializationException oluşturur.

Aşağıdaki örnek, "REGEX_DEFAULT_MATCH_TIMEOUT" özelliğine atanan değer geçersiz olduğunda atılan değerini gösterir TypeInitializationException . Özel durumu ortadan kaldırmak için"REGEX_DEFAULT_MATCH_TIMEOUT" özelliğini sıfırdan büyük ve yaklaşık 24 günden kısa bir TimeSpan değere ayarlayın.

using System;
using System.Text.RegularExpressions;

public class RegexEx1
{
    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()
open System
open System.Text.RegularExpressions

let domain = AppDomain.CurrentDomain
// Set a timeout interval of -2 seconds.
domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds -2)

let rgx = Regex "[aeiouy]"
printfn $"Regular expression pattern: {rgx}"
printfn $"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds"
// 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 Example4
    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()

Takvimler ve kültürel veriler

Bir takvimin örneğini oluşturmayı denerseniz ancak çalışma zamanı bu takvime karşılık gelen nesnenin CultureInfo örneğini oluşturamazsa, bir TypeInitializationException özel durum oluşturur. Bu özel durum aşağıdaki takvim sınıfı oluşturucuları tarafından oluşturulabilir:

Bu kültürlere yönelik kültürel veriler tüm sistemlerde kullanılabilir olması gerektiğinden, bu özel durumla nadiren karşılaşmalısınız.