InvalidCastException Classe
Definizione
Eccezione generata per una conversione esplicita o un cast non valido.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
- Ereditarietà
- Ereditarietà
- Attributi
Commenti
.NET Framework supporta la conversione automatica dai tipi derivati ai relativi tipi di base e viceversa al tipo derivato, nonché dai tipi che presentano le interfacce agli oggetti interfaccia e viceversa..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. Include anche un'ampia gamma di meccanismi che supportano le conversioni personalizzate.It also includes a variety of mechanisms that support custom conversions. Per ulteriori informazioni, vedere conversione di tipi in .NET Framework.For more information, see Type Conversion in .NET Framework.
Viene generata un'eccezione InvalidCastException quando la conversione di un'istanza di un tipo in un altro non è supportata.An InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. Ad esempio, se si tenta di convertire un Char valore in un valore, viene DateTime generata un' InvalidCastException eccezione.For example, attempting to convert a Char value to a DateTime value throws an InvalidCastException exception. Differisce da un'eccezione OverflowException, che viene generata quando la conversione di un tipo in un altro è supportata, ma il valore del tipo di origine non è compreso nell'intervallo del tipo di destinazione.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. Un' InvalidCastException eccezione è causata dall'errore dello sviluppatore e non deve essere gestita in un try/catch
blocco.An InvalidCastException exception is caused by developer error and should not be handled in a try/catch
block. È invece consigliabile eliminare la ragione dell'eccezione.Instead, the cause of the exception should be eliminated.
Per informazioni sulle conversioni supportate dal sistema, vedere la classe Convert.For information about conversions supported by the system, see the Convert class. Per gli errori che si verificano quando il tipo di destinazione può archiviare i valori del tipo di origine, ma non è sufficientemente grande da archiviare un valore di origine specifico, vedere l' OverflowException eccezione.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.
Nota
In molti casi, il compilatore di linguaggio rileva che non è possibile alcuna conversione tra il tipo di origine e il tipo di destinazione e genera un errore del compilatore.In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error.
Le sezioni seguenti illustrano alcune delle condizioni in base alle quali una conversione tentata genera un' InvalidCastException eccezione:Some of the conditions under which an attempted conversion throws an InvalidCastException exception are discussed in the following sections:
- Tipi primitivi e IConvertiblePrimitive types and IConvertible
- Metodo Convert. ChangeTypeThe Convert.ChangeType method
- Conversioni verso un tipo di applicazione più piccolo e implementazioni IConvertibleNarrowing conversions and IConvertible implementations
- DowncastDowncasting
- Conversione da un oggetto di interfacciaConversion from an interface object
- Conversioni di stringheString conversions
- Migrazione di Visual Basic 6,0Visual Basic 6.0 migration
Affinché una conversione esplicita di un riferimento abbia esito positivo, il valore di origine deve essere null
oppure il tipo di oggetto a cui fa riferimento l'argomento di origine deve essere convertibile nel tipo di destinazione mediante una conversione implicita di riferimento.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.
Le seguenti istruzioni del linguaggio intermedio (IL) generano un'eccezione InvalidCastException:The following intermediate language (IL) instructions throw an InvalidCastException exception:
castclass
refanyval
unbox
InvalidCastException USA HRESULT COR_E_INVALIDCAST, che ha il valore 0x80004002.InvalidCastException uses the HRESULT COR_E_INVALIDCAST, which has the value 0x80004002.
Per un elenco di valori di proprietà iniziali per un'istanza di InvalidCastException, vedere il InvalidCastException costruttori.For a list of initial property values for an instance of InvalidCastException, see the InvalidCastException constructors.
Tipi primitivi e IConvertiblePrimitive types and IConvertible
Viene chiamata direttamente o indirettamente l'implementazione IConvertible di un tipo primitivo che non supporta una determinata conversione.You directly or indirectly call a primitive type's IConvertible implementation that does not support a particular conversion. Ad esempio, il tentativo di convertire un valore Boolean in Char o un valore DateTime in Int32 genera un'eccezione InvalidCastException.For example, trying to convert a Boolean value to a Char or a DateTime value to an Int32 throws an InvalidCastException exception. Nell'esempio seguente vengono chiamati i metodi Boolean.IConvertible.ToChar e Convert.ToChar(Boolean) per convertire un valore Boolean in Char.The following example calls both the Boolean.IConvertible.ToChar and Convert.ToChar(Boolean) methods to convert a Boolean value to a Char. In entrambi i casi, la chiamata al metodo genera un'eccezione InvalidCastException.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.
Poiché la conversione non è supportata, non esiste alcuna soluzione alternativa.Because the conversion is not supported, there is no workaround.
Metodo Convert. ChangeTypeThe Convert.ChangeType method
È stato chiamato il metodo Convert.ChangeType per convertire un oggetto da un tipo in un altro, ma uno o entrambi i tipi non implementano l'interfaccia IConvertible.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.
Nella maggior parte dei casi, poiché la conversione non è supportata, non esiste alcuna soluzione alternativa.In most cases, because the conversion is not supported, there is no workaround. In alcuni casi, una possibile soluzione alternativa consiste nell'assegnare manualmente i valori di proprietà dal tipo di origine a proprietà simili di un tipo di destinazione.In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type.
Conversioni verso un tipo di applicazione più piccolo e implementazioni IConvertibleNarrowing conversions and IConvertible implementations
Gli operatori di restringimento definiscono le conversioni esplicite supportate da un tipo.Narrowing operators define the explicit conversions supported by a type. Per eseguire la conversione è necessario un operatore di cast in C# o il CType
metodo di conversione in Visual Basic (se Option Strict
è on).A casting operator in C# or the CType
conversion method in Visual Basic (if Option Strict
is on) is required to perform the conversion.
Tuttavia, se né il tipo di origine né quello di destinazione definiscono una conversione esplicita o verso un tipo di dati più piccolo tra i due tipi e l' IConvertible implementazione di uno o entrambi i tipi non supporta una conversione dal tipo di origine al tipo di destinazione, InvalidCastException viene generata un'eccezione.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.
Nella maggior parte dei casi, poiché la conversione non è supportata, non esiste alcuna soluzione alternativa.In most cases, because the conversion is not supported, there is no workaround.
DowncastDowncasting
Si sta eseguendo un downcast, ovvero si sta provando a convertire un'istanza di un tipo di base in una dei relativi tipi derivati.You are downcasting, that is, trying to convert an instance of a base type to one of its derived types. Nell'esempio seguente, il tentativo di convertire un oggetto Person
in un oggetto PersonWithID
ha esito negativo.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.
Come illustrato nell'esempio, il downcast ha esito positivo solo se l'oggetto Person
è stato creato da un upcast di un oggetto PersonWithId
in un oggetto Person
o se l'oggetto Person
è 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
.
Conversione da un oggetto di interfacciaConversion from an interface object
Si sta tentando di convertire un oggetto di interfaccia in un tipo che implementa tale interfaccia, ma il tipo di destinazione non è dello stesso tipo o di una classe di base del tipo da cui l'oggetto interfaccia è stato originariamente derivato.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. Nell'esempio seguente viene generata un' InvalidCastException eccezione quando si tenta di convertire un IFormatProvider oggetto in un DateTimeFormatInfo oggetto.The following example throws an InvalidCastException exception when it attempts to convert an IFormatProvider object to a DateTimeFormatInfo object. La conversione non riesce perché, sebbene la DateTimeFormatInfo classe implementi l' IFormatProvider interfaccia, l' DateTimeFormatInfo oggetto non è correlato alla CultureInfo classe da cui è derivato l'oggetto interfaccia.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()
Come indicato dal messaggio di eccezione, la conversione avrà esito positivo solo se l'oggetto interfaccia viene riconvertito in un'istanza del tipo originale, in questo 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. La conversione ha esito positivo anche se l'oggetto interfaccia viene convertito in un'istanza di un tipo di base del tipo originale.The conversion would also succeed if the interface object is converted to an instance of a base type of the original type.
Conversioni di stringheString conversions
Si sta provando a convertire un valore o un oggetto nella relativa rappresentazione di stringa usando un operatore di cast in C#.You are trying to convert a value or an object to its string representation by using a casting operator in C#. Nell'esempio seguente, sia il tentativo di eseguire il cast Char di un valore a una stringa che il tentativo di eseguire il cast di un valore integer a una stringa generano un' InvalidCastException eccezione.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;
}
}
Nota
L'uso dell' CStr
operatore Visual Basic per convertire un valore di un tipo primitivo in una stringa ha esito positivo.Using the Visual Basic CStr
operator to convert a value of a primitive type to a string succeeds. L'operazione non genera un' InvalidCastException eccezione.The operation does not throw an InvalidCastException exception.
Per convertire correttamente un'istanza di qualsiasi tipo nella relativa rappresentazione di stringa, chiamare ToString
il relativo metodo, come nell'esempio seguente.To successfully convert an instance of any type to its string representation, call its ToString
method, as the following example does. Il ToString
metodo è sempre presente poiché il ToString metodo è definito dalla Object classe e pertanto viene ereditato o sottoposto a override da tutti i tipi gestiti.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
Migrazione di Visual Basic 6,0Visual Basic 6.0 migration
Si sta aggiornando un'applicazione Visual Basic 6,0 con una chiamata a un evento personalizzato in un controllo utente per Visual Basic .NET e InvalidCastException viene generata un'eccezione con il messaggio "cast specificato non valido".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." Per eliminare questa eccezione, modificare la riga di codice nel form, Form1
ad esempioTo eliminate this exception, change the line of code in your form (such as Form1
)
Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5))
e sostituirlo con la seguente riga di codice:and replace it with the following line of code:
Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5))
Costruttori
InvalidCastException() |
Inizializza una nuova istanza della classe InvalidCastException.Initializes a new instance of the InvalidCastException class. |
InvalidCastException(SerializationInfo, StreamingContext) |
Inizializza una nuova istanza della classe InvalidCastException con dati serializzati.Initializes a new instance of the InvalidCastException class with serialized data. |
InvalidCastException(String) |
Inizializza una nuova istanza della classe InvalidCastException con un messaggio di errore specificato.Initializes a new instance of the InvalidCastException class with a specified error message. |
InvalidCastException(String, Exception) |
Inizializza una nuova istanza della classe InvalidCastException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.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) |
Inizializza una nuova istanza della classe InvalidCastException con un messaggio e il codice di errore specificati.Initializes a new instance of the InvalidCastException class with a specified message and error code. |
Proprietà
Data |
Ottiene una raccolta di coppie chiave/valore che forniscono informazioni definite dall'utente aggiuntive sull'eccezione.Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Ereditato da Exception) |
HelpLink |
Ottiene o imposta un collegamento al file della Guida associato all'eccezione.Gets or sets a link to the help file associated with this exception. (Ereditato da Exception) |
HResult |
Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato a un'eccezione specifica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Ereditato da Exception) |
InnerException |
Ottiene l'istanza di Exception che ha causato l'eccezione corrente.Gets the Exception instance that caused the current exception. (Ereditato da Exception) |
Message |
Ottiene un messaggio che descrive l'eccezione corrente.Gets a message that describes the current exception. (Ereditato da Exception) |
Source |
Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.Gets or sets the name of the application or the object that causes the error. (Ereditato da Exception) |
StackTrace |
Ottiene una rappresentazione di stringa dei frame immediati nello stack di chiamate.Gets a string representation of the immediate frames on the call stack. (Ereditato da Exception) |
TargetSite |
Ottiene il metodo che genera l'eccezione corrente.Gets the method that throws the current exception. (Ereditato da Exception) |
Metodi
Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object. (Ereditato da Object) |
GetBaseException() |
Quando ne viene eseguito l'override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Ereditato da Exception) |
GetHashCode() |
Funge da funzione hash predefinita.Serves as the default hash function. (Ereditato da Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Quando ne viene eseguito l'override in una classe derivata, imposta il controllo SerializationInfo con le informazioni sull'eccezione.When overridden in a derived class, sets the SerializationInfo with information about the exception. (Ereditato da Exception) |
GetType() |
Ottiene il tipo di runtime dell'istanza corrente.Gets the runtime type of the current instance. (Ereditato da Exception) |
MemberwiseClone() |
Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object. (Ereditato da Object) |
ToString() |
Crea e restituisce una rappresentazione di stringa dell'eccezione corrente.Creates and returns a string representation of the current exception. (Ereditato da Exception) |
Eventi
SerializeObjectState |
Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Ereditato da Exception) |