InvalidCastException Classe
Definição
A exceção que é gerada para projeção inválida ou conversão explícita.The exception that is thrown for invalid casting or explicit conversion.
public ref class InvalidCastException : Exception
public ref class InvalidCastException : SystemException
public class InvalidCastException : Exception
public class InvalidCastException : SystemException
[System.Serializable]
public class InvalidCastException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class InvalidCastException : SystemException
type InvalidCastException = class
inherit Exception
type InvalidCastException = class
inherit SystemException
[<System.Serializable>]
type InvalidCastException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type InvalidCastException = class
inherit SystemException
Public Class InvalidCastException
Inherits Exception
Public Class InvalidCastException
Inherits SystemException
- Herança
- Herança
- Atributos
Comentários
O .NET Framework dá suporte à conversão automática de tipos derivados para seus tipos base e de volta para o tipo derivado, bem como de tipos que apresentam interfaces para objetos de interface e de volta..NET Framework supports automatic conversion from derived types to their base types and back to the derived type, as well as from types that present interfaces to interface objects and back. Ele também inclui uma variedade de mecanismos que dão suporte a conversões personalizadas.It also includes a variety of mechanisms that support custom conversions. Para obter mais informações, consulte conversão de tipo em .NET Framework.For more information, see Type Conversion in .NET Framework.
Uma InvalidCastException exceção é lançada quando a conversão de uma instância de um tipo para outro tipo não é suportada.An InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. Por exemplo, tentar converter um Char valor em um DateTime valor gera uma InvalidCastException exceção.For example, attempting to convert a Char value to a DateTime value throws an InvalidCastException exception. Ele é diferente de uma OverflowException exceção, que é lançada quando há suporte para uma conversão de um tipo para outro, mas o valor do tipo de origem está fora do intervalo do tipo de destino.It differs from an OverflowException exception, which is thrown when a conversion of one type to another is supported, but the value of the source type is outside the range of the target type. Uma InvalidCastException exceção é causada por um erro do desenvolvedor e não deve ser manipulada em um try/catch
bloco.An InvalidCastException exception is caused by developer error and should not be handled in a try/catch
block. Em vez disso, a causa da exceção deve ser eliminada.Instead, the cause of the exception should be eliminated.
Para obter informações sobre conversões com suporte no sistema, consulte a Convert classe.For information about conversions supported by the system, see the Convert class. Para erros que ocorrem quando o tipo de destino pode armazenar valores de tipo de origem, mas não é grande o suficiente para armazenar um valor de origem específico, consulte a OverflowException exceção.For errors that occur when the destination type can store source type values but is not large enough to store a specific source value, see the OverflowException exception.
Observação
Em muitos casos, o seu compilador de linguagem detecta que não existe conversão entre o tipo de origem e o tipo de destino e emite um erro de compilador.In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error.
Algumas das condições sob as quais uma tentativa de conversão gera uma InvalidCastException exceção são discutidas nas seções a seguir:Some of the conditions under which an attempted conversion throws an InvalidCastException exception are discussed in the following sections:
- Tipos primitivos e IConvertiblePrimitive types and IConvertible
- O método Convert. AltertypeThe Convert.ChangeType method
- Restringir conversões e implementações de IConvertibleNarrowing conversions and IConvertible implementations
- DowncastingDowncasting
- Conversão de um objeto de interfaceConversion from an interface object
- Conversões de cadeia de caracteresString conversions
- Migração do Visual Basic 6,0Visual Basic 6.0 migration
Para que uma conversão de referência explícita seja bem-sucedida, o valor de origem deve ser null
ou o tipo de objeto referenciado pelo argumento de origem deve ser conversível para o tipo de destino por uma conversão de referência implícita.For an explicit reference conversion to be successful, the source value must be null
, or the object type referenced by the source argument must be convertible to the destination type by an implicit reference conversion.
As instruções de IL (linguagem intermediária) a seguir geram uma InvalidCastException exceção:The following intermediate language (IL) instructions throw an InvalidCastException exception:
castclass
refanyval
unbox
InvalidCastException usa o COR_E_INVALIDCAST HRESULT, que tem o valor 0x80004002.InvalidCastException uses the HRESULT COR_E_INVALIDCAST, which has the value 0x80004002.
Para obter uma lista de valores de propriedade inicial para uma instância do InvalidCastException, consulte o InvalidCastException construtores.For a list of initial property values for an instance of InvalidCastException, see the InvalidCastException constructors.
Tipos primitivos e IConvertiblePrimitive types and IConvertible
Você chama direta ou indiretamente uma implementação de tipo primitivo IConvertible que não oferece suporte a uma conversão em particular.You directly or indirectly call a primitive type's IConvertible implementation that does not support a particular conversion. Por exemplo, tentar converter um Boolean valor em um Char ou um DateTime valor para um Int32 gera uma InvalidCastException exceção.For example, trying to convert a Boolean value to a Char or a DateTime value to an Int32 throws an InvalidCastException exception. O exemplo a seguir chama os Boolean.IConvertible.ToChar Convert.ToChar(Boolean) métodos e para converter um Boolean valor em um Char .The following example calls both the Boolean.IConvertible.ToChar and Convert.ToChar(Boolean) methods to convert a Boolean value to a Char. Em ambos os casos, a chamada do método gera uma InvalidCastException exceção.In both cases, the method call throws an InvalidCastException exception.
using System;
public class Example
{
public static void Main()
{
bool flag = true;
try {
IConvertible conv = flag;
Char ch = conv.ToChar(null);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Boolean to a Char.");
}
try {
Char ch = Convert.ToChar(flag);
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Boolean to a Char.");
}
}
}
// The example displays the following output:
// Cannot convert a Boolean to a Char.
// Cannot convert a Boolean to a Char.
Module Example
Public Sub Main()
Dim flag As Boolean = True
Try
Dim conv As IConvertible = flag
Dim ch As Char = conv.ToChar(Nothing)
Console.WriteLine("Conversion succeeded.")
Catch e As InvalidCastException
Console.WriteLine("Cannot convert a Boolean to a Char.")
End Try
Try
Dim ch As Char = Convert.ToChar(flag)
Console.WriteLine("Conversion succeeded.")
Catch e As InvalidCastException
Console.WriteLine("Cannot convert a Boolean to a Char.")
End Try
End Sub
End Module
' The example displays the following output:
' Cannot convert a Boolean to a Char.
' Cannot convert a Boolean to a Char.
Como não há suporte para a conversão, não há nenhuma solução alternativa.Because the conversion is not supported, there is no workaround.
O método Convert. AltertypeThe Convert.ChangeType method
Você chamou o Convert.ChangeType método para converter um objeto de um tipo para outro, mas um ou ambos os tipos não implementam a IConvertible interface.You've called the Convert.ChangeType method to convert an object from one type to another, but one or both types don't implement the IConvertible interface.
Na maioria dos casos, como a conversão não tem suporte, não há nenhuma solução alternativa.In most cases, because the conversion is not supported, there is no workaround. Em alguns casos, uma possível solução alternativa é atribuir manualmente valores de Propriedade do tipo de origem a propriedades semelhantes de um tipo de destino.In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type.
Restringir conversões e implementações de IConvertibleNarrowing conversions and IConvertible implementations
Os operadores de restrição definem as conversões explícitas com suporte por um tipo.Narrowing operators define the explicit conversions supported by a type. Um operador de elenco em C# ou o CType
método de conversão em Visual Basic (if Option Strict
is on) é necessário para executar a conversão.A casting operator in C# or the CType
conversion method in Visual Basic (if Option Strict
is on) is required to perform the conversion.
No entanto, se nem o tipo de origem nem o tipo de destino definirem uma conversão explícita ou restrita entre os dois tipos, e a IConvertible implementação de um ou ambos os tipos não oferecer suporte a uma conversão do tipo de origem para o tipo de destino, uma InvalidCastException exceção será lançada.However, if neither the source type nor the target type defines an explicit or narrowing conversion between the two types, and the IConvertible implementation of one or both types doesn't support a conversion from the source type to the target type, an InvalidCastException exception is thrown.
Na maioria dos casos, como a conversão não tem suporte, não há nenhuma solução alternativa.In most cases, because the conversion is not supported, there is no workaround.
DowncastingDowncasting
Você está Downcasting, ou seja, tentar converter uma instância de um tipo base para um de seus tipos derivados.You are downcasting, that is, trying to convert an instance of a base type to one of its derived types. No exemplo a seguir, a tentativa de converter um Person
objeto em um PersonWithID
objeto falha.In the following example, trying to convert a Person
object to a PersonWithID
object fails.
using System;
public class Person
{
String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
}
public class PersonWithId : Person
{
String _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
}
public class Example
{
public static void Main()
{
Person p = new Person();
p.Name = "John";
try {
PersonWithId pid = (PersonWithId) p;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
PersonWithId pid1 = new PersonWithId();
pid1.Name = "John";
pid1.Id = "246";
Person p1 = pid1;
try {
PersonWithId pid1a = (PersonWithId) p1;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
Person p2 = null;
try {
PersonWithId pid2 = (PersonWithId) p2;
Console.WriteLine("Conversion succeeded.");
}
catch (InvalidCastException) {
Console.WriteLine("Conversion failed.");
}
}
}
// The example displays the following output:
// Conversion failed.
// Conversion succeeded.
// Conversion succeeded.
Public Class Person
Dim _name As String
Public Property Name As String
Get
Return _name
End Get
Set
_name = value
End Set
End Property
End Class
Public Class PersonWithID : Inherits Person
Dim _id As String
Public Property Id As String
Get
Return _id
End Get
Set
_id = value
End Set
End Property
End Class
Module Example
Public Sub Main()
Dim p As New Person()
p.Name = "John"
Try
Dim pid As PersonWithId = CType(p, PersonWithId)
Console.WriteLine("Conversion succeeded.")
Catch e As InvalidCastException
Console.WriteLine("Conversion failed.")
End Try
Dim pid1 As New PersonWithId()
pid1.Name = "John"
pid1.Id = "246"
Dim p1 As Person = pid1
Try
Dim pid1a As PersonWithId = CType(p1, PersonWithId)
Console.WriteLine("Conversion succeeded.")
Catch e As InvalidCastException
Console.WriteLine("Conversion failed.")
End Try
Dim p2 As Person = Nothing
Try
Dim pid2 As PersonWithId = CType(p2, PersonWithId)
Console.WriteLine("Conversion succeeded.")
Catch e As InvalidCastException
Console.WriteLine("Conversion failed.")
End Try
End Sub
End Module
' The example displays the following output:
' Conversion failed.
' Conversion succeeded.
' Conversion succeeded.
Como mostra o exemplo, o downcast só terá êxito se o Person
objeto tiver sido criado por um upcast de um PersonWithId
objeto para um Person
objeto ou se o Person
objeto for null
.As the example shows, the downcast succeeds only if the Person
object was created by an upcast from a PersonWithId
object to a Person
object, or if the Person
object is null
.
Conversão de um objeto de interfaceConversion from an interface object
Você está tentando converter um objeto de interface em um tipo que implementa essa interface, mas o tipo de destino não é do mesmo tipo ou uma classe base do tipo do qual o objeto de interface foi originalmente derivado.You are attempting to convert an interface object to a type that implements that interface, but the target type is not the same type or a base class of the type from which the interface object was originally derived. O exemplo a seguir gera uma InvalidCastException exceção ao tentar converter um IFormatProvider objeto em um DateTimeFormatInfo objeto.The following example throws an InvalidCastException exception when it attempts to convert an IFormatProvider object to a DateTimeFormatInfo object. A conversão falha porque, embora a DateTimeFormatInfo classe implemente a IFormatProvider interface, o DateTimeFormatInfo objeto não está relacionado à CultureInfo classe da qual o objeto de interface foi derivado.The conversion fails because although the DateTimeFormatInfo class implements the IFormatProvider interface, the DateTimeFormatInfo object is not related to the CultureInfo class from which the interface object was derived.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
var culture = CultureInfo.InvariantCulture;
IFormatProvider provider = culture;
DateTimeFormatInfo dt = (DateTimeFormatInfo) provider;
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidCastException:
// Unable to cast object of type //System.Globalization.CultureInfo// to
// type //System.Globalization.DateTimeFormatInfo//.
// at Example.Main()
Imports System.Globalization
Module Example
Public Sub Main()
Dim culture As CultureInfo = CultureInfo.InvariantCulture
Dim provider As IFormatProvider = culture
Dim dt As DateTimeFormatInfo = CType(provider, DateTimeFormatInfo)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidCastException:
' Unable to cast object of type 'System.Globalization.CultureInfo' to
' type 'System.Globalization.DateTimeFormatInfo'.
' at Example.Main()
À medida que a mensagem de exceção indica, a conversão seria bem sucedido apenas se o objeto da interface fosse convertido de volta em uma instância do tipo original, neste caso, a CultureInfo .As the exception message indicates, the conversion would succeed only if the interface object is converted back to an instance of the original type, in this case a CultureInfo. A conversão também terá sucesso se o objeto da interface fosse convertido em uma instância de um tipo base do tipo original.The conversion would also succeed if the interface object is converted to an instance of a base type of the original type.
Conversões de cadeia de caracteresString conversions
Você está tentando converter um valor ou um objeto em sua representação de cadeia de caracteres usando um operador de conversão em C#.You are trying to convert a value or an object to its string representation by using a casting operator in C#. No exemplo a seguir, a tentativa de converter um Char valor em uma cadeia de caracteres e a tentativa de converter um inteiro em uma cadeia de caracteres gera uma InvalidCastException exceção.In the following example, both the attempt to cast a Char value to a string and the attempt to cast an integer to a string throw an InvalidCastException exception.
using System;
public class Example
{
public static void Main()
{
object value = 12;
// Cast throws an InvalidCastException exception.
string s = (string) value;
}
}
Observação
O uso do CStr
operador Visual Basic para converter um valor de um tipo primitivo em uma cadeia de caracteres é executado com sucesso.Using the Visual Basic CStr
operator to convert a value of a primitive type to a string succeeds. A operação não gera uma InvalidCastException exceção.The operation does not throw an InvalidCastException exception.
Para converter com êxito uma instância de qualquer tipo em sua representação de cadeia de caracteres, chame seu ToString
método, como faz o exemplo a seguir.To successfully convert an instance of any type to its string representation, call its ToString
method, as the following example does. O ToString
método está sempre presente, pois o ToString método é definido pela Object classe e, portanto, é herdado ou substituído por todos os tipos gerenciados.The ToString
method is always present, since the ToString method is defined by the Object class and therefore is either inherited or overridden by all managed types.
using System;
public class Example
{
public static void Main()
{
object value = 12;
string s = value.ToString();
Console.WriteLine(s);
}
}
// The example displays the following output:
// 12
Migração do Visual Basic 6,0Visual Basic 6.0 migration
Você está atualizando um aplicativo Visual Basic 6,0 com uma chamada para um evento personalizado em um controle de usuário para Visual Basic .NET e uma InvalidCastException exceção é gerada com a mensagem "a conversão especificada não é válida".You're upgrading a Visual Basic 6.0 application with a call to a custom event in a user control to Visual Basic .NET, and an InvalidCastException exception is thrown with the message, "Specified cast is not valid." Para eliminar essa exceção, altere a linha de código no formulário (como Form1
)To eliminate this exception, change the line of code in your form (such as Form1
)
Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5))
e substitua-o pela seguinte linha de código:and replace it with the following line of code:
Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5))
Construtores
InvalidCastException() |
Inicializa uma nova instância da classe InvalidCastException.Initializes a new instance of the InvalidCastException class. |
InvalidCastException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da classe InvalidCastException com dados serializados.Initializes a new instance of the InvalidCastException class with serialized data. |
InvalidCastException(String) |
Inicializa uma nova instância da classe InvalidCastException com uma mensagem de erro especificada.Initializes a new instance of the InvalidCastException class with a specified error message. |
InvalidCastException(String, Exception) |
Inicializa uma nova instância da classe InvalidCastException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa da exceção.Initializes a new instance of the InvalidCastException class with a specified error message and a reference to the inner exception that is the cause of this exception. |
InvalidCastException(String, Int32) |
Inicializa uma nova instância da classe InvalidCastException com uma mensagem e um código de erro especificados.Initializes a new instance of the InvalidCastException class with a specified message and error code. |
Propriedades
Data |
Obtém uma coleção de pares de chave/valor que fornecem informações definidas pelo usuário adicionais sobre a exceção.Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Herdado de Exception) |
HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção.Gets or sets a link to the help file associated with this exception. (Herdado de Exception) |
HResult |
Obtém ou define HRESULT, um valor numérico codificado que é atribuído a uma exceção específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Herdado de Exception) |
InnerException |
Obtém a instância Exception que causou a exceção atual.Gets the Exception instance that caused the current exception. (Herdado de Exception) |
Message |
Obtém uma mensagem que descreve a exceção atual.Gets a message that describes the current exception. (Herdado de Exception) |
Source |
Obtém ou define o nome do aplicativo ou objeto que causa o erro.Gets or sets the name of the application or the object that causes the error. (Herdado de Exception) |
StackTrace |
Obtém uma representação de cadeia de caracteres de quadros imediatos na pilha de chamadas.Gets a string representation of the immediate frames on the call stack. (Herdado de Exception) |
TargetSite |
Obtém o método que gerou a exceção atual.Gets the method that throws the current exception. (Herdado de Exception) |
Métodos
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception que é a causa raiz de uma ou mais exceções subsequentes.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Herdado de Exception) |
GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção.When overridden in a derived class, sets the SerializationInfo with information about the exception. (Herdado de Exception) |
GetType() |
Obtém o tipo de runtime da instância atual.Gets the runtime type of the current instance. (Herdado de Exception) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
ToString() |
Cria e retorna uma representação de cadeia de caracteres da exceção atual.Creates and returns a string representation of the current exception. (Herdado de Exception) |
Eventos
SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Herdado de Exception) |