TypeLoadException Construtores

Definição

Inicializa uma nova instância da TypeLoadException classe.

Sobrecargas

Name Description
TypeLoadException()

Inicializa uma nova instância da TypeLoadException classe.

TypeLoadException(String)

Inicializa uma nova instância da TypeLoadException classe com uma mensagem de erro especificada.

TypeLoadException(SerializationInfo, StreamingContext)

Inicializa uma nova instância da TypeLoadException classe com dados serializados.

TypeLoadException(String, Exception)

Inicializa uma nova instância da TypeLoadException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção.

TypeLoadException()

Inicializa uma nova instância da TypeLoadException classe.

public:
 TypeLoadException();
public TypeLoadException();
Public Sub New ()

Observações

Este construtor inicializa a Message propriedade da nova instância numa mensagem fornecida pelo sistema que descreve o erro, como "Ocorreu uma falha durante o carregamento de um tipo." Esta mensagem tem em conta a cultura atual do sistema.

A tabela seguinte mostra os valores iniciais das propriedades para uma instância de TypeLoadException.

Property Value
InnerException Uma referência nula (Nothing em Visual Basic).
Message A cadeia de mensagens de erro localizadas.

Aplica-se a

TypeLoadException(String)

Inicializa uma nova instância da TypeLoadException classe com uma mensagem de erro especificada.

public:
 TypeLoadException(System::String ^ message);
public TypeLoadException(string message);
new TypeLoadException : string -> TypeLoadException
Public Sub New (message As String)

Parâmetros

message
String

A mensagem que descreve o erro.

Exemplos

O seguinte exemplo de código demonstra o TypeLoadException(String) construtor. Contém um método que gera uma TypeLoadException mensagem personalizada e apresenta a mensagem de erro para a consola.

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.

Observações

O conteúdo do message parâmetro deve ser compreensível para o utilizador. O chamador deste construtor é obrigado a garantir que esta cadeia foi localizada para a cultura do sistema atual.

A tabela seguinte mostra os valores iniciais das propriedades para uma instância de TypeLoadException.

Property Value
InnerException Uma referência nula (Nothing em Visual Basic).
Message A cadeia de mensagens de erro.

Aplica-se a

TypeLoadException(SerializationInfo, StreamingContext)

Inicializa uma nova instância da TypeLoadException classe com dados 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);
new TypeLoadException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> TypeLoadException
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Parâmetros

info
SerializationInfo

O objeto que contém os dados do objeto serializado.

context
StreamingContext

A informação contextual sobre a origem ou destino.

Exceções

O info objetivo é null.

Exemplos

O exemplo seguinte gera uma exceção, serializa os dados da exceção para um ficheiro e depois reconstitui a exceção. Para que este exemplo de código seja executado, deve fornecer o nome de assembleia totalmente qualificado. Para informações sobre como obter o nome de assembleia totalmente qualificado, consulte Nomes de Assembleia.


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

Observações

Este construtor é chamado durante a desserialização para reconstituir o objeto exceção transmitido através de um fluxo. Para mais informações, consulte XML e Serialização SOAP.

Ver também

Aplica-se a

TypeLoadException(String, Exception)

Inicializa uma nova instância da TypeLoadException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção.

public:
 TypeLoadException(System::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

A mensagem de erro que explica a razão da exceção.

inner
Exception

A exceção que é a causa da exceção atual. Se o inner parâmetro não nullfor , a exceção atual é elevada num catch bloco que gere a exceção interna.

Exemplos

O seguinte exemplo de código demonstra o TypeLoadException(String, Exception) construtor. Contém um método que gera uma TypeLoadException, apanha essa exceção e lança uma nova TypeLoadException com uma mensagem personalizada, incluindo a original TypeLoadException como exceção interna.

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

Observações

Uma exceção que seja lançada como resultado direto de uma exceção anterior pode incluir uma referência à exceção anterior na InnerException propriedade. A InnerException propriedade devolve o mesmo valor que é passado ao construtor, ou null se a InnerException propriedade não fornecer o valor de exceção interna ao construtor.

A tabela seguinte mostra os valores iniciais das propriedades para uma instância de TypeLoadException.

Property Value
InnerException A referência à exceção interna.
Message A cadeia de mensagens de erro.

Ver também

Aplica-se a