InvalidCastException InvalidCastException InvalidCastException InvalidCastException Class

定义

因无效类型转换或显式转换引发的异常。The exception that is thrown for invalid casting or explicit conversion.

public ref class InvalidCastException : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class InvalidCastException : SystemException
type InvalidCastException = class
    inherit SystemException
Public Class InvalidCastException
Inherits SystemException
继承
InvalidCastExceptionInvalidCastExceptionInvalidCastExceptionInvalidCastException
属性

注解

.NET Framework 支持从派生类型转换为其基类型为派生的类型,以及提供接口进行交互的对象并返回的类型自动转换。The .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. 它还包括各种支持的自定义转换的机制。It also includes a variety of mechanisms that support custom conversions. 有关详细信息,请参阅.NET Framework 中的类型转换For more information, see Type Conversion in the .NET Framework.

InvalidCastException不支持的一种类型的实例转换为另一种类型时引发异常。An InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. 例如,尝试将转换Char值设为DateTime值,则会引发InvalidCastException异常。For example, attempting to convert a Char value to a DateTime value throws an InvalidCastException exception. 它不同于OverflowException支持到另一种类型的转换,但源类型的值超出了目标类型的范围时引发的异常。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. InvalidCastException异常由开发人员错误,并且不应处理中try/catch阻止; 相反,应消除异常的原因。An InvalidCastException exception is caused by developer error and should not be handled in a try/catch block; instead, the cause of the exception should be eliminated.

有关系统支持的转换的信息,请参阅Convert类。For information about conversions supported by the system, see the Convert class. 有关源类型值,但不是大型目标类型可以存储时出现的错误不足以存储特定的源值,请参阅OverflowException异常。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.

备注

在许多情况下,你的语言编译器检测到任何转换的源类型与目标类型之间存在并会发出编译器错误。In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error.

一些条件尝试执行的转换会引发在其下InvalidCastException以下各节中讨论了异常:Some of the conditions under which an attempted conversion throws an InvalidCastException exception are discussed in the following sections:

基元类型和 IConvertible Primitive types and IConvertible
Convert.ChangeType 方法 The Convert.ChangeType method
收缩转换和 IConvertible 实现 Narrowing conversions and IConvertible implementations
向下转换 Downcasting
从接口对象的转换 Conversion from an interface object
字符串转换 String conversions
Visual Basic 6.0 迁移Visual Basic 6.0 migration

对于显式引用转换成功,源值必须为null,或由源参数引用的对象类型必须可转换为目标类型的隐式引用转换。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.

以下的中间语言 (IL) 指令引发InvalidCastException异常:The following intermediate language (IL) instructions throw an InvalidCastException exception:

  • castclass

  • refanyval

  • unbox

InvalidCastException 使用 HRESULT COR_E_INVALIDCAST,其值 0x80004002。InvalidCastException uses the HRESULT COR_E_INVALIDCAST, which has the value 0x80004002.

有关实例的初始属性值的列表InvalidCastException,请参阅InvalidCastException构造函数。For a list of initial property values for an instance of InvalidCastException, see the InvalidCastException constructors.

基元类型和 IConvertiblePrimitive types and IConvertible

直接或间接调用基元类型的IConvertible不支持特定转换的实现。You directly or indirectly call a primitive type's IConvertible implementation that does not support a particular conversion. 例如,尝试将转换Boolean值设为CharDateTime值设置为Int32引发InvalidCastException异常。For example, trying to convert a Boolean value to a Char or a DateTime value to an Int32 throws an InvalidCastException exception. 下面的示例调用两Boolean.IConvertible.ToCharConvert.ToChar(Boolean)进行转换的方法Boolean值设为CharThe following example calls both the Boolean.IConvertible.ToChar and Convert.ToChar(Boolean) methods to convert a Boolean value to a Char. 在这两种情况下,该方法调用将引发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.

由于支持转换,没有解决方法。Because the conversion is not supported, there is no workaround.

Convert.ChangeType 方法The Convert.ChangeType method

已调用Convert.ChangeType方法将对象从一种类型到另一个,但一个或两种类型不实现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.

在大多数情况下,由于支持转换,没有解决方法。In most cases, because the conversion is not supported, there is no workaround. 在某些情况下,可能的解决方法是手动将属性值的源类型分配给的类似属性的目标类型。In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type.

收缩转换和 IConvertible 实现Narrowing conversions and IConvertible implementations

收缩运算符定义类型支持的显式转换。Narrowing operators define the explicit conversions supported by a type. 在 C# 强制转换运算符或CType在 Visual Basic 中的转换方法 (如果Option Strict上) 所需执行转换。A casting operator in C# or the CType conversion method in Visual Basic (if Option Strict is on) is required to perform the conversion.

但是,如果源类型既不目标类型定义的显式或收缩的两个类型之间的转换和IConvertible的一个或两种类型的实现不支持从的源类型转换为目标类型, InvalidCastException引发异常。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.

在大多数情况下,由于支持转换,没有解决方法。In most cases, because the conversion is not supported, there is no workaround.

向下转换Downcasting

您将向下转换,即,尝试将基类型的实例转换为其派生类型之一。You are downcasting, that is, trying to convert an instance of a base type to one of its derived types. 在以下示例中,尝试将转换Person对象传递给PersonWithID对象失败。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.

如示例所示,向下转换时才会成功Person对象从向上转换来创建PersonWithId对象传递给Person对象,或者如果Person对象是nullAs 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.

从接口对象的转换Conversion from an interface object

尝试将接口对象转换为类型实现该接口,但目标类型不是相同类型或接口对象最初从其派生的类型的基类。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. 下面的示例将引发InvalidCastException异常时它会尝试转换IFormatProvider对象传递给DateTimeFormatInfo对象。The following example throws an InvalidCastException exception when it attempts to convert an IFormatProvider object to a DateTimeFormatInfo object. 转换失败,因为尽管DateTimeFormatInfo类实现IFormatProvider接口,DateTimeFormatInfo对象不与CultureInfo类从它派生的接口对象。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()

作为异常消息指示,接口对象转换回原始类型的实例,在这种情况下,才会成功转换CultureInfoAs 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. 如果接口对象转换为原始类型的基类型的实例,也会成功完成转换。The conversion would also succeed if the interface object is converted to an instance of a base type of the original type.

字符串转换String conversions

要为其字符串表示形式中转换值或对象,在 C# 中使用强制转换运算符。You are trying to convert a value or an object to its string representation by using a casting operator in C#. 在下面的示例中,这两个尝试强制转换Char值为字符串,并尝试强制转换到字符串抛出一个整数,InvalidCastException异常。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;
   }
}

备注

使用 Visual BasicCStr运算符将基元类型的值转换为字符串成功。Using the Visual Basic CStr operator to convert a value of a primitive type to a string succeeds. 该操作不会引发InvalidCastException异常。The operation does not throw an InvalidCastException exception.

为成功转换为其字符串表示形式的任何类型的实例,请在调用其ToString方法,如下面的示例执行。To successfully covert an instance of any type to its string representation, call its ToString method, as the following example does. ToString方法将始终存在,因为ToString方法由定义Object类并因此继承或重写由下列所有托管类型。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

Visual Basic 6.0 迁移Visual Basic 6.0 migration

您具有对用户控件中的自定义事件的调用的 Visual Basic 6.0 应用程序升级到 Visual Basic.NET 和InvalidCastException引发异常并显示消息,"指定的转换无效。"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." 若要消除此异常,更改你的窗体中的代码行 (如Form1)To eliminate this exception, change the line of code in your form (such as Form1)

Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5))  

并将其替换为以下代码行:and replace it with the following line of code:

Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5))  

构造函数

InvalidCastException() InvalidCastException() InvalidCastException() InvalidCastException()

初始化 InvalidCastException 类的新实例。Initializes a new instance of the InvalidCastException class.

InvalidCastException(SerializationInfo, StreamingContext) InvalidCastException(SerializationInfo, StreamingContext) InvalidCastException(SerializationInfo, StreamingContext) InvalidCastException(SerializationInfo, StreamingContext)

用序列化数据初始化 InvalidCastException 类的新实例。Initializes a new instance of the InvalidCastException class with serialized data.

InvalidCastException(String) InvalidCastException(String) InvalidCastException(String) InvalidCastException(String)

用指定的错误消息初始化 InvalidCastException 类的新实例。Initializes a new instance of the InvalidCastException class with a specified error message.

InvalidCastException(String, Exception) InvalidCastException(String, Exception) InvalidCastException(String, Exception) InvalidCastException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 InvalidCastException 类的新实例。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) InvalidCastException(String, Int32) InvalidCastException(String, Int32) InvalidCastException(String, Int32)

使用指定的消息和错误代码初始化 InvalidCastException 类的新实例。Initializes a new instance of the InvalidCastException class with a specified message and error code.

属性

Data Data Data Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

获取描述当前异常的消息。Gets a message that describes the current exception.

(Inherited from Exception)
Source Source Source Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(Inherited from Exception)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType() GetType() GetType() GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception.

(Inherited from Exception)

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

适用于

另请参阅