TypeInitializationException Clase

Definición

Excepción que se produce como un contenedor alrededor de la excepción producida por el inicializador de clase. Esta clase no puede heredarse.

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
Herencia
TypeInitializationException
Herencia
TypeInitializationException
Atributos

Comentarios

Cuando un inicializador de clase no puede inicializar un tipo, TypeInitializationException se crea y se pasa una referencia a la excepción producida por el inicializador de clase del tipo. La InnerException propiedad de TypeInitializationException contiene la excepción subyacente.

Normalmente, la TypeInitializationException excepción refleja una condición grave (el tiempo de ejecución no puede crear instancias de un tipo) que impide que una aplicación continúe. Normalmente, TypeInitializationException se produce en respuesta a algún cambio en el entorno en ejecución de la aplicación. Por lo tanto, aparte de posiblemente para resolver problemas relacionados con el código de depuración, la excepción no debe gestionarse en un try/catch bloque. En su lugar, la causa de la excepción debe investigarse y eliminarse.

TypeInitializationException usa HRESULT COR_E_TYPEINITIALIZATION, que tiene el valor 0x80131534.

Para obtener una lista de valores de propiedad iniciales para una instancia de TypeInitializationException, vea los TypeInitializationException constructores.

En las secciones siguientes se describen algunas de las situaciones en las que se produce una TypeInitializationException excepción.

Constructores estáticos

El tiempo de ejecución llama automáticamente a un constructor estático, si existe, antes de crear una nueva instancia de un tipo. Un desarrollador puede definir explícitamente constructores estáticos. Si un constructor estático no se define explícitamente, los compiladores crean automáticamente uno para inicializar cualquier static miembro (en C# o F#) o Shared (en Visual Basic) del tipo. Para obtener más información sobre los constructores estáticos, vea Constructores estáticos.

Normalmente, se produce una TypeInitializationException excepción cuando un constructor estático no puede crear instancias de un tipo. La InnerException propiedad indica por qué el constructor estático no pudo crear instancias del tipo. Algunas de las causas más comunes de una TypeInitializationException excepción son:

  • Una excepción no controlada en un constructor estático

    Si se inicia una excepción en un constructor estático, se encapsula en una excepción TypeInitializationException y no se puede crear una instancia del tipo.

    Lo que a menudo dificulta la solución de problemas de esta excepción es que los constructores estáticos no siempre se definen explícitamente en el código fuente. Existe un constructor estático en un tipo si:

    • Se ha definido explícitamente como miembro de un tipo.

    • El tipo tiene static variables (en C# o F#) o Shared (en Visual Basic) que se declaran e inicializan en una sola instrucción. En este caso, el compilador de lenguaje genera un constructor estático para el tipo . Por ejemplo, cuando los compiladores de C# y VB compilan el ejemplo siguiente, generan el IL para un constructor estático similar al siguiente:

      .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
      

    En el ejemplo siguiente se muestra una TypeInitializationException excepción producida por un constructor estático generado por el compilador. La Example clase incluye un campo static (en C#) o Shared (en Visual Basic) de tipo TestClass, que se instancia pasando un valor de 3 a su constructor de clase. Sin embargo, ese valor es ilegal; solo se permiten valores de 0 o 1. Como resultado, el constructor de clase TestClass inicia una excepción ArgumentOutOfRangeException. Dado que esta excepción no se controla, se encapsula en una TypeInitializationException excepción.

    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))
            End If
            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()
    

    El mensaje de excepción muestra información sobre la InnerException propiedad .

  • Falta un ensamblado o un archivo de datos

    Una causa común de una TypeInitializationException excepción es la ausencia de un ensamblado o un archivo de datos que estaba presente en los entornos de desarrollo y pruebas de una aplicación, pero falta en su entorno de ejecución. Por ejemplo, puede compilar el ejemplo siguiente en un ensamblado denominado Missing1a.dll mediante esta sintaxis de línea de comandos:

    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
    

    A continuación, puede compilar el ejemplo siguiente en un archivo ejecutable denominado Missing1.exe incluyendo una referencia a Missing1a.dll:

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

    Sin embargo, si cambia el nombre, mueve o elimina Missing1a.dll y ejecuta el ejemplo, produce una TypeInitializationException excepción y muestra la salida que se muestra en el ejemplo. Tenga en cuenta que el mensaje de excepción incluye información sobre la InnerException propiedad . En este caso, la excepción interna es una FileNotFoundException que se lanza porque el entorno de ejecución no puede localizar el ensamblado dependiente.

    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()
    

    Note

    En este ejemplo, se ha iniciado una excepción TypeInitializationException porque no se ha podido cargar un ensamblado. También se puede producir la excepción si un constructor estático intenta abrir un archivo de datos, como un archivo de configuración, un archivo XML o un archivo que contiene datos serializados, que no puede encontrar.

Valores de tiempo de espera de coincidencia de expresiones regulares

Puede establecer el valor de tiempo de espera predeterminado para una operación de coincidencia de patrones de expresión regular por dominio de aplicación. El tiempo de espera se define mediante una especificación de un TimeSpan valor para la propiedad "REGEX_DEFAULT_MATCH_TIMEOUT" en el AppDomain.SetData método . El intervalo de tiempo debe ser un objeto válido TimeSpan que sea mayor que cero y menor que aproximadamente 24 días. Si no se cumplen estos requisitos, el intento de establecer el valor de tiempo de espera predeterminado produce un ArgumentOutOfRangeException, que a su vez se encapsula en una TypeInitializationException excepción.

En el ejemplo siguiente se muestra el TypeInitializationException que se lanza cuando el valor asignado a la propiedad "REGEX_DEFAULT_MATCH_TIMEOUT" no es válido. Para eliminar la excepción, establezca la propiedad "REGEX_DEFAULT_MATCH_TIMEOUT" en un TimeSpan valor mayor que cero y menor que aproximadamente 24 días.

using System;
using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;

public class RegexEx1
{
    public static void Run()
    {
        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 'AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains the invalid value or object
//       '-00:00:02' 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, CultureInfo culture)
//       at RegexEx1.Run()
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()

Calendarios y datos culturales

Si intenta crear una instancia de un calendario, pero el tiempo de ejecución no puede crear una instancia del CultureInfo objeto que corresponde a ese calendario, produce una TypeInitializationException excepción. Esta excepción puede ser lanzada por los constructores de las clases de calendario siguientes:

Dado que los datos culturales de estas culturas deben estar disponibles en todos los sistemas, rara vez, si acaso, debería usted encontrar esta excepción.

Constructores

Nombre Description
TypeInitializationException(String, Exception)

Inicializa una nueva instancia de la TypeInitializationException clase con el mensaje de error predeterminado, el nombre de tipo especificado y una referencia a la excepción interna que es la causa principal de esta excepción.

Propiedades

Nombre Description
Data

Obtiene una colección de pares clave-valor que proporcionan información adicional definida por el usuario sobre la excepción.

(Heredado de Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.

(Heredado de Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.

(Heredado de Exception)
InnerException

Obtiene la Exception instancia que provocó la excepción actual.

(Heredado de Exception)
Message

Obtiene un mensaje que describe la excepción actual.

(Heredado de Exception)
Source

Obtiene o establece el nombre de la aplicación o el objeto que provoca el error.

(Heredado de Exception)
StackTrace

Obtiene una representación de cadena de los fotogramas inmediatos en la pila de llamadas.

(Heredado de Exception)
TargetSite

Obtiene el método que produce la excepción actual.

(Heredado de Exception)
TypeName

Obtiene el nombre completo del tipo que no se puede inicializar.

Métodos

Nombre Description
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetBaseException()

Cuando se reemplaza en una clase derivada, devuelve la Exception causa principal de una o varias excepciones posteriores.

(Heredado de Exception)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Establece el SerializationInfo objeto con el nombre de tipo y la información de excepción adicional.

GetType()

Obtiene el tipo de tiempo de ejecución de la instancia actual.

(Heredado de Exception)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual.

(Heredado de Exception)

Eventos

Nombre Description
SerializeObjectState
Obsoletos.

Se produce cuando se serializa una excepción para crear un objeto de estado de excepción que contiene datos serializados sobre la excepción.

(Heredado de Exception)

Se aplica a

Consulte también