InvalidCastException 類別

定義

無效的轉型或明確轉換所擲回的例外狀況。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
繼承
InvalidCastException
繼承
InvalidCastException
屬性

備註

.NET Framework 支援從衍生型別轉換為其基底類型,再轉換回衍生型別,以及從呈現介面物件之介面的類型,再轉換回衍生型別。.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 .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 值時會擲回例外狀況 InvalidCastExceptionFor 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:

若要讓明確的參考轉換成功,來源值必須是 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 Char 例外狀況 DateTime Int32 InvalidCastExceptionFor 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) 以將值轉換為 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.

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. 在下列範例中,嘗試將物件轉換 PersonPersonWithID 物件失敗。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

您正在嘗試將介面物件轉換為實該介面的型別,但是目標型別不是相同的型別,也是介面物件原本衍生的型別基類(base class)。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 DateTimeFormatInfoThe 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 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 convert an instance of any type to its string representation, call its ToString method, as the following example does. ToString方法一律會存在,因為 ToString 方法是由類別所定義, Object 因此是由所有 managed 類型繼承或覆寫。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 類別的新執行個體。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()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen 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)

適用於

另請參閱