InvalidCastException InvalidCastException InvalidCastException InvalidCastException Class

定義

無效的轉型 (Casting) 或明確轉換所擲回的例外狀況。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.

當不支援將某個類型的實例轉換成另一種類型時, 就會擲回例外狀況(exception)。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
從介面物件轉換 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例如, 嘗試將值轉換CharInt32DateTime值至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)方法, 以CharBoolean值轉換為。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#的轉型運算子或CType Visual Basic 中的轉換方法 ( 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.

向下檢視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方法是由類別所定義, 因此會由所有 managed 類型繼承或覆寫。 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() 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()

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

適用於

另請參閱