TypeLoadException Constructores
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Inicializa una nueva instancia de la clase TypeLoadException.
Sobrecargas
TypeLoadException() |
Inicializa una nueva instancia de la clase TypeLoadException. |
TypeLoadException(String) |
Inicializa una nueva instancia de la clase TypeLoadException con el mensaje de error especificado. |
TypeLoadException(SerializationInfo, StreamingContext) |
Obsoletos.
Inicializa una nueva instancia de la clase TypeLoadException con datos serializados. |
TypeLoadException(String, Exception) |
Inicializa una nueva instancia de la clase TypeLoadException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción. |
TypeLoadException()
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
Inicializa una nueva instancia de la clase TypeLoadException.
public:
TypeLoadException();
public TypeLoadException ();
Public Sub New ()
Comentarios
Este constructor inicializa la Message propiedad de la nueva instancia en un mensaje proporcionado por el sistema que describe el error, como "Se ha producido un error al cargar un tipo". Este mensaje tiene en cuenta la referencia cultural del sistema actual.
En la tabla siguiente se muestran los valores de propiedad iniciales para una instancia de TypeLoadException.
Propiedad | Value |
---|---|
InnerException | Referencia nula (Nothing en Visual Basic). |
Message | La cadena del mensaje de error localizado. |
Se aplica a
TypeLoadException(String)
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
Inicializa una nueva instancia de la clase TypeLoadException con el mensaje de error especificado.
public:
TypeLoadException(System::String ^ message);
public TypeLoadException (string message);
public TypeLoadException (string? message);
new TypeLoadException : string -> TypeLoadException
Public Sub New (message As String)
Parámetros
- message
- String
Mensaje que describe el error.
Ejemplos
En el ejemplo de código siguiente se muestra el TypeLoadException(String) constructor . Contiene un método que genera un TypeLoadException con un mensaje personalizado y muestra el mensaje de error en la consola.
using namespace System;
class TypeLoadExceptionDemoClass
{
public:
static bool GenerateException()
{
// Throw a TypeLoadException with a custom message.
throw gcnew TypeLoadException("This is a custom TypeLoadException error message.");
}
};
int main()
{
try {
// Call a method that throws an exception.
TypeLoadExceptionDemoClass::GenerateException();
}
catch ( TypeLoadException^ e ) {
Console::WriteLine("TypeLoadException:\n {0}", e->Message);
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: \n\tError Message = {0}", e->Message );
}
}
// The example displays the following output:
// TypeLoadException:
// This is a custom TypeLoadException error message.
using System;
public class Example
{
public static void Main()
{
try {
// Call a method that throws an exception.
TypeLoadExceptionDemoClass.GenerateException();
}
catch (TypeLoadException e) {
Console.WriteLine("TypeLoadException:\n {0}", e.Message);
}
}
}
class TypeLoadExceptionDemoClass
{
public static bool GenerateException()
{
// Throw a TypeLoadException with a custom defined message.
throw new TypeLoadException("This is a custom TypeLoadException error message.");
}
}
// The example displays the following output:
// TypeLoadException:
// This is a custom TypeLoadException error message.
Public Class Example
Public Shared Sub Main()
Try
' Call a method that throws an exception.
TypeLoadExceptionDemoClass.GenerateException()
Catch e As TypeLoadException
Console.WriteLine("TypeLoadException:{0} {1}", vbCrLf, e.Message)
End Try
End Sub
End Class
Class TypeLoadExceptionDemoClass
Public Shared Function GenerateException() As Boolean
' Throw a TypeLoadException with a custom message.
Throw New TypeLoadException("This is a custom TypeLoadException error message.")
End Function
End Class
' The example displays the following output:
' TypeLoadException:
' This is a custom TypeLoadException error message.
Comentarios
El contenido del message
parámetro debe ser comprensible para el usuario. El autor de llamada de este constructor debe asegurarse de que esta cadena se ha adaptado para la referencia cultural del sistema actual.
En la tabla siguiente se muestran los valores de propiedad iniciales para una instancia de TypeLoadException.
Propiedad | Value |
---|---|
InnerException | Referencia nula (Nothing en Visual Basic). |
Message | Cadena con el mensaje de error. |
Se aplica a
TypeLoadException(SerializationInfo, StreamingContext)
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
Precaución
This API supports obsolete formatter-based serialization. It should not be called or extended by application code.
Inicializa una nueva instancia de la clase TypeLoadException con datos serializados.
protected:
TypeLoadException(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected TypeLoadException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected TypeLoadException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new TypeLoadException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> TypeLoadException
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new TypeLoadException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> TypeLoadException
Protected Sub New (info As SerializationInfo, context As StreamingContext)
Parámetros
- info
- SerializationInfo
Objeto que contiene los datos del objeto serializados.
- context
- StreamingContext
Información contextual acerca del origen o del destino.
- Atributos
Excepciones
El objeto info
es null
.
Ejemplos
En el ejemplo siguiente se genera una excepción y se serializan los datos de excepción en un archivo y, a continuación, se reconstituye la excepción. Para que se ejecute este ejemplo de código, debe proporcionar el nombre completo del ensamblado. Para obtener información sobre cómo obtener el nombre completo del ensamblado, vea Nombres de ensamblado.
#using <System.Runtime.Serialization.Formatters.Soap.dll>
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Soap;
using namespace System::IO;
// This class overrides the GetObjectData method and initializes
// its data with current time.
[Serializable]
public ref class MyTypeLoadExceptionChild: public TypeLoadException
{
public:
System::DateTime ErrorDateTime;
MyTypeLoadExceptionChild()
{
ErrorDateTime = DateTime::Now;
}
MyTypeLoadExceptionChild( DateTime myDateTime )
{
ErrorDateTime = myDateTime;
}
protected:
MyTypeLoadExceptionChild( SerializationInfo^ sInfo, StreamingContext * sContext )
{
// Reconstitute the deserialized information into the instance.
ErrorDateTime = sInfo->GetDateTime( "ErrorDate" );
}
public:
void GetObjectData( SerializationInfo^ sInfo, StreamingContext * sContext )
{
// Add a value to the Serialization information.
sInfo->AddValue( "ErrorDate", ErrorDateTime );
}
};
int main()
{
// Load the mscorlib assembly and get a reference to it.
// You must supply the fully qualified assembly name for mscorlib.dll here.
Assembly^ myAssembly = Assembly::Load( "Assembly text name, Version, Culture, PublicKeyToken" );
try
{
Console::WriteLine( "Attempting to load a type not present in the assembly 'mscorlib'" );
// This loading of invalid type raises a TypeLoadException
Type^ myType = myAssembly->GetType( "System::NonExistentType", true );
}
catch ( TypeLoadException^ )
{
// Serialize the exception to disk and reconstitute it back again.
try
{
System::DateTime ErrorDatetime = DateTime::Now;
Console::WriteLine( "A TypeLoadException has been raised." );
// Create MyTypeLoadException instance with current time.
MyTypeLoadExceptionChild^ myTypeLoadExceptionChild = gcnew MyTypeLoadExceptionChild( ErrorDatetime );
IFormatter^ myFormatter = gcnew SoapFormatter;
Stream^ myFileStream = gcnew FileStream( "typeload.xml",FileMode::Create,FileAccess::Write,FileShare::None );
Console::WriteLine( "Serializing the TypeLoadException with DateTime as {0}", ErrorDatetime );
// Serialize the MyTypeLoadException instance to a file.
myFormatter->Serialize( myFileStream, myTypeLoadExceptionChild );
myFileStream->Close();
Console::WriteLine( "Deserializing the Exception." );
myFileStream = gcnew FileStream( "typeload.xml",FileMode::Open,FileAccess::Read,FileShare::None );
// Deserialize and reconstitute the instance from file.
myTypeLoadExceptionChild = safe_cast<MyTypeLoadExceptionChild^>(myFormatter->Deserialize( myFileStream ));
myFileStream->Close();
Console::WriteLine( "Deserialized exception has ErrorDateTime = {0}", myTypeLoadExceptionChild->ErrorDateTime );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e->Message );
}
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
class GetObjectDataDemo
{
public static void Main()
{
// Get a reference to the assembly mscorlib.dll, which is always
// loaded. (System.String is defined in mscorlib.)
Assembly mscorlib = typeof(string).Assembly;
try
{
Console.WriteLine ("Attempting to load a type not present in the assembly 'mscorlib'");
// This loading of invalid type raises a TypeLoadException
Type myType = mscorlib.GetType("System.NonExistentType", true);
}
catch (TypeLoadException)
{
// Serialize the exception to disk and reconstitute it.
System.DateTime ErrorDatetime = DateTime.Now;
Console.WriteLine("A TypeLoadException has been raised.");
// Create MyTypeLoadException instance with current time.
MyTypeLoadException myException = new MyTypeLoadException(ErrorDatetime);
IFormatter myFormatter = new SoapFormatter();
Stream myFileStream = new FileStream("typeload.xml", FileMode.Create, FileAccess.Write, FileShare.None);
Console.WriteLine("Serializing the TypeLoadException with DateTime as " + ErrorDatetime);
// Serialize the MyTypeLoadException instance to a file.
myFormatter.Serialize(myFileStream, myException);
myFileStream.Close();
Console.WriteLine("Deserializing the Exception.");
myFileStream = new FileStream("typeload.xml", FileMode.Open, FileAccess.Read, FileShare.None);
// Deserialize and reconstitute the instance from file.
myException = (MyTypeLoadException) myFormatter.Deserialize(myFileStream);
myFileStream.Close();
Console.WriteLine("Deserialized exception has ErrorDateTime = " + myException.ErrorDateTime);
}
}
}
// This class overrides the GetObjectData method and initializes
// its data with current time.
[Serializable]
public class MyTypeLoadException : TypeLoadException
{
private System.DateTime _errorDateTime = DateTime.Now;
public DateTime ErrorDateTime { get { return _errorDateTime; }}
public MyTypeLoadException(DateTime myDateTime)
{
_errorDateTime = myDateTime;
}
protected MyTypeLoadException(SerializationInfo sInfo, StreamingContext sContext)
: base(sInfo, sContext)
{
// Reconstitute the deserialized information into the instance.
_errorDateTime = sInfo.GetDateTime("ErrorDate");
}
public override void GetObjectData(SerializationInfo sInfo, StreamingContext sContext)
{
base.GetObjectData(sInfo, sContext);
// Add a value to the Serialization information.
sInfo.AddValue("ErrorDate", ErrorDateTime);
}
}
Imports System.Reflection
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Security.Permissions
Imports System.IO
Class GetObjectDataDemo
Public Shared Sub Main()
' Get a reference to the assembly mscorlib.dll, which is always
' loaded. (System.String is defined in mscorlib.)
Dim tString As Type = GetType(String)
Dim mscorlib As [Assembly] = tString.Assembly
Try
Console.WriteLine("Attempting to load a type not present in the assembly 'mscorlib'")
' This loading of invalid type raises a TypeLoadException
Dim myType As Type = mscorlib.GetType("System.NonExistentType", True)
Catch
' Serialize the exception to disk and reconstitute it.
Dim ErrorDatetime as System.DateTime = DateTime.Now
Console.WriteLine("A TypeLoadException has been raised.")
' Create MyTypeLoadException instance with current time.
Dim myException As new MyTypeLoadException(ErrorDatetime)
Dim myFormatter as IFormatter = new SoapFormatter()
Dim myFileStream as Stream
myFileStream = New FileStream("typeload.xml", FileMode.Create, FileAccess.Write, FileShare.None)
Console.WriteLine("Serializing the TypeLoadException with DateTime as " _
& ErrorDatetime.ToString())
' Serialize the MyTypeLoadException instance to a file.
myFormatter.Serialize(myFileStream, myException)
myFileStream.Close()
Console.WriteLine("Deserializing the Exception.")
myFileStream = New FileStream("typeload.xml", FileMode.Open, FileAccess.Read, FileShare.None)
' Deserialize and reconstitute the instance from file.
myException = CType(myFormatter.Deserialize(myFileStream), MyTypeLoadException)
myFileStream.Close()
Console.WriteLine("Deserialized exception has ErrorDateTime = " + myException.ErrorDateTime.ToString())
End Try
End Sub
End Class
' This class overrides the GetObjectData method and initializes
' its data with current time.
<Serializable()> _
Public Class MyTypeLoadException
Inherits TypeLoadException
Private _errorDateTime As System.DateTime = DateTime.Now
Public ReadOnly Property ErrorDateTime As DateTime
Get
Return _errorDateTime
End Get
End Property
Public Sub New(myDateTime As DateTime)
_errorDateTime = myDateTime
End Sub
Protected Sub New(sInfo As SerializationInfo, sContext As StreamingContext)
MyBase.New(sInfo, sContext)
' Reconstitute the deserialized information into the instance.
_errorDateTime = sInfo.GetDateTime("ErrorDate")
End Sub
' GetObjectData overrides must always have a demand for SerializationFormatter.
<SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter:=true)> _
Public Overrides Sub GetObjectData(sInfo As SerializationInfo, sContext As StreamingContext)
MyBase.GetObjectData(sInfo, sContext)
' Add a value to the Serialization information.
sInfo.AddValue("ErrorDate", ErrorDateTime)
End Sub
End Class
Comentarios
Se llama a este constructor durante la deserialización para reconstituir el objeto de excepción transmitido en un flujo. Para obtener más información, consulte Serialización XML y SOAP.
Consulte también
Se aplica a
TypeLoadException(String, Exception)
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
- Source:
- TypeLoadException.cs
Inicializa una nueva instancia de la clase TypeLoadException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción.
public:
TypeLoadException(System::String ^ message, Exception ^ inner);
public TypeLoadException (string message, Exception inner);
public TypeLoadException (string? message, Exception? inner);
new TypeLoadException : string * Exception -> TypeLoadException
Public Sub New (message As String, inner As Exception)
Parámetros
- message
- String
Mensaje de error que explica el motivo de la excepción.
- inner
- Exception
Excepción que es la causa de la excepción actual. Si el parámetro inner
no es null
, la excepción actual se produce en un bloque catch
que controla la excepción interna.
Ejemplos
En el ejemplo de código siguiente se muestra el TypeLoadException(String, Exception) constructor . Contiene un método que genera un TypeLoadException, detecta esa excepción y genera un nuevo TypeLoadException con un mensaje personalizado, incluido el original TypeLoadException como excepción interna.
using namespace System;
using namespace System::Runtime::InteropServices;
ref class TypeLoadExceptionDemoClass
{
public:
// A call to this method will raise a TypeLoadException.
[DllImport("NonExistentDLL.DLL",EntryPoint="MethodNotExists")]
static void NonExistentMethod();
static void GenerateException()
{
try
{
NonExistentMethod();
}
catch ( TypeLoadException^ e )
{
// Rethrow exception with the exception as inner exception
throw gcnew TypeLoadException( "This exception was raised due to a call to an invalid method.",e );
}
}
};
int main()
{
Console::WriteLine( "Calling a method in a non-existent DLL which triggers a TypeLoadException." );
try
{
TypeLoadExceptionDemoClass::GenerateException();
}
catch ( TypeLoadException^ e )
{
Console::WriteLine( "TypeLoadException: \n\tError Message = {0}", e->Message );
Console::WriteLine( "TypeLoadException: \n\tInnerException Message = {0}", e->InnerException->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: \n\tError Message = {0}", e->Message );
}
}
using System;
using System.Runtime.InteropServices;
public class TypeLoadException_Constructor3
{
public static void Main()
{
Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.");
try
{
TypeLoadExceptionDemoClass3.GenerateException();
}
catch (TypeLoadException e)
{
Console.WriteLine ("TypeLoadException: \n\tError Message = " + e.Message);
Console.WriteLine ("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message );
}
catch (Exception e)
{
Console.WriteLine ("Exception: \n\tError Message = " + e.Message);
}
}
}
class TypeLoadExceptionDemoClass3
{
// A call to this method will raise a TypeLoadException.
[DllImport("NonExistentDLL.DLL", EntryPoint="MethodNotExists")]
public static extern void NonExistentMethod();
public static void GenerateException()
{
try
{
NonExistentMethod();
}
catch (TypeLoadException e)
{
// Rethrow exception with the exception as inner exception
throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e);
}
}
}
Imports System.Runtime.InteropServices
Public Class TypeLoadException_Constructor3
Public Shared Sub Main()
Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.")
Try
TypeLoadExceptionDemoClass.GenerateException()
Catch e As TypeLoadException
Console.WriteLine(("TypeLoadException: " + ControlChars.Cr + ControlChars.Tab + "Error Message = " + e.Message))
Console.WriteLine(("TypeLoadException: " + ControlChars.Cr + ControlChars.Tab + "InnerException Message = " + e.InnerException.Message))
Catch e As Exception
Console.WriteLine(("Exception: " + ControlChars.Cr + ControlChars.Tab + "Error Message = " + e.Message))
End Try
End Sub
End Class
Class TypeLoadExceptionDemoClass
' A call to this method will raise a TypeLoadException.
Public Declare Sub NonExistentMethod Lib "NonExistentDLL.DLL" Alias "MethodNotExists" ()
Public Shared Sub GenerateException()
Try
NonExistentMethod()
Catch e As TypeLoadException
' Rethrow exception with the exception as inner exception
Throw New TypeLoadException("This exception was raised due to a call to an invalid method.", e)
End Try
End Sub
End Class
Comentarios
Una excepción que se produce como resultado directo de una excepción anterior puede incluir una referencia a la excepción anterior de la propiedad InnerException. La propiedad InnerException devuelve el mismo valor que se haya pasado al constructor, o bien null
en caso de que la propiedad InnerException no le haya proporcionado al constructor el valor de la excepción interna.
En la tabla siguiente se muestran los valores de propiedad iniciales para una instancia de TypeLoadException.
Propiedad | Valor |
---|---|
InnerException | Referencia a la excepción interna. |
Message | Cadena con el mensaje de error. |