Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
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 atılan istisnanın bir referansı geçirilir. InnerException özelliği TypeInitializationException tarafından temel alınan özel durumu tutar.
Genellikle, TypeInitializationException özel durumu, bir uygulamanın devam etmesini engelleyen yıkıcı bir 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, muhtemelen hata ayıklama kodunu çözmek için dışında, özel durum bir try
/catch
bloğunda işlenmemelidir. Bunun yerine, özel durumun nedeni araştırılmalı ve ortadan kaldırılmalıdır.
TypeInitializationException değeri 0x80131534 olan HRESULT COR_E_TYPEINITIALIZATION
kullanır.
TypeInitializationExceptionörneğinin ilk özellik değerlerinin listesi için bkz. TypeInitializationException oluşturucuları.
Aşağıdaki bölümlerde, TypeInitializationException özel durumunun oluştuğu bazı durumlar 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 static
(C# veya F#'da) veya Shared
(Visual Basic'te) üyelerini başlatmak için otomatik olarak bir oluşturucu oluşturur. Statik oluşturucular hakkında daha fazla bilgi için bkz. Statik Oluşturucular.
En yaygın olarak, statik bir oluşturucu bir tür örneği oluşturamadığında bir TypeInitializationException özel durumu oluşturulur. InnerException özelliği, statik oluşturucunun türü neden örnekleyemediğini gösterir. TypeInitializationException özel durumunun daha yaygın nedenlerinden bazıları şunlardır:
Statik oluşturucuda işlenmeyen özel durum
Statik bir oluşturucuda bir özel durum fırlatılırsa, bu özel durum bir TypeInitializationException özel durumu ile sarılır ve tür yapılamaz.
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 ifadede bildirilen ve başlatılmış
static
(C# veya F#'da) veyaShared
(Visual Basic'te) değişkenleri vardır. Bu durumda, dil derleyicisi türü için statik bir oluşturucu oluşturur. IL Disassemblergibi 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 örnek, derleyici tarafından oluşturulan statik bir oluşturucu ile atılan bir TypeInitializationException istisnasını göstermektedir.
Example
sınıfı, sınıf yapıcısına 3 değeri geçirilerek örneklenen,static
türünde birShared
(C#'ta) veyaTestClass
(Visual Basic'te) alan içerir. 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 durumu içine 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 InnerException özelliği hakkındaki bilgileri görüntülediğine dikkat edin.
Eksik bir derleme veya veri dosyası
TypeInitializationException özel durumunun yaygın bir nedeni, uygulamanın geliştirme ve test ortamlarında bulunan bir derlemenin 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'e bir referans 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ırsanız, taşırsanız veya silerseniz ve örneği çalıştırırsanız, TypeInitializationException özel durumu atar ve örnekte gösterilen çıktıyı görüntüler. Özel durum iletisinin InnerException özelliği hakkında bilgi içerdiğini unutmayın. Bu durumda, çalışma zamanı bağımlı derlemeyi bulamadığından oluşturulan iç istisna bir FileNotFoundException'dır.
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()
Uyarı
Bu örnekte, bir derleme yüklenemediği için bir TypeInitializationException özel durumu 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ı, TimeSpan yönteminde "REGEX_DEFAULT_MATCH_TIMEOUT" özelliği için bir AppDomain.SetData değeri belirtilerek tanımlanır. Zaman aralığı, sıfırdan büyük ve yaklaşık 24 günden kısa geçerli bir TimeSpan nesnesi olmalıdır. Bu gereksinimler karşılanmazsa, varsayılan zaman aşımı değerini ayarlama girişimi bir ArgumentOutOfRangeExceptionoluşturur ve bu da bir TypeInitializationException özel durumuyla sarmalanır.
Aşağıdaki örnekte, "REGEX_DEFAULT_MATCH_TIMEOUT" özelliğine atanan değer geçersiz olduğunda atılan TypeInitializationException gösterilmektedir. Ö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ğerine 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: {rgx.ToString()}");
Console.WriteLine($"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()
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 CultureInfo nesnesinin örneğini oluşturamazsa, bir TypeInitializationException istisnası atılır. Bu özel durum aşağıdaki takvim sınıfı oluşturucuları tarafından oluşturulabilir:
- JapaneseCalendar sınıfının parametresiz oluşturucu.
- KoreanCalendar sınıfının parametresiz oluşturucu.
- TaiwanCalendar sınıfının parametresiz oluşturucu.
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.