InvalidCastException 类

定义

因无效类型转换或显式转换引发的异常。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
继承
InvalidCastException
属性

注解

.NET Framework 支持从派生类型到其基类型的自动转换, 并可返回到派生的类型, 以及向 interface 对象和背面提供接口的类型的自动转换。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.

不支持将一种类型的实例转换为另一种类型时, 将引发异常。InvalidCastExceptionAn 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. 异常是由开发人员错误引起的, 不应try/catch在块中进行处理; 相反, 应该消除异常的原因。 InvalidCastExceptionAn 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
ChangeType 方法 The Convert.ChangeType method
收缩转换和 IConvertible 实现 Narrowing conversions and IConvertible implementations
Downcasting 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使用 COR_E_INVALIDCAST 值为0x80004002 的 HRESULT。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例如, 尝试将值转换Char为或DateTime将值转换为时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.ToChar调用和Convert.ToChar(Boolean)方法将BooleanChar转换为。The 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.

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#的转换运算符或 Visual Basic CType (如果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.

但是, 如果源类型和目标类型都不定义两个类型之间的显式转换或收缩转换, 并且一个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.

DowncastingDowncasting

你是 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对象为时, 才会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.

从接口对象转换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()

如异常消息所示, 仅当接口对象转换回原始类型 (在本例中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. 如果接口对象转换为原始类型的基类型的实例, 则此转换也会成功。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 Basic CStr运算符可将基元类型的值转换为字符串。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因为Object方法由类定义, 因此由所有托管类型继承或重写。 ToStringThe 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 类的新实例。Initializes a new instance of the InvalidCastException class.

InvalidCastException(SerializationInfo, StreamingContext)

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

InvalidCastException(String)

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

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 类的新实例。Initializes a new instance of the InvalidCastException class with a specified message and error code.

属性

Data

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

(继承自 Exception)
HelpLink

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

(继承自 Exception)
HResult

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

(继承自 Exception)
InnerException

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

(继承自 Exception)
Message

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

(继承自 Exception)
Source

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

(继承自 Exception)
StackTrace

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

(继承自 Exception)
TargetSite

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

(继承自 Exception)

方法

Equals(Object)

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

(继承自 Object)
GetBaseException()

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

(继承自 Exception)
GetHashCode()

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

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

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

(继承自 Exception)
GetType()

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

(继承自 Exception)
MemberwiseClone()

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

(继承自 Object)
ToString()

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

(继承自 Exception)

事件

SerializeObjectState

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

(继承自 Exception)

适用于

另请参阅