InvalidCastException 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
無效的轉型或明確轉換所擲回的例外狀況。
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
- 繼承
- 繼承
- 屬性
備註
.NET Framework支援從衍生類型自動轉換成其基底類型,以及從呈現介面物件和返回介面介面之介面的類型轉換回衍生型別。 它也包含支援自訂轉換的各種機制。 如需詳細資訊,請參閱.NET Framework 中的類型轉換。
InvalidCastException不支援將某個型別的實例轉換成另一個型別時,就會擲回例外狀況。 例如,嘗試將值 DateTime 轉換成 Char 值會 InvalidCastException 擲回例外狀況。 它與例外狀況不同,當支援將某個類型轉換成另一個 OverflowException 類型時擲回,但來源類型的值超出目標型別的範圍。 InvalidCastException例外狀況是由開發人員錯誤所造成,不應在 區塊中 try/catch
處理。 相反地,應該消除例外狀況的原因。
如需系統所支援轉換的相關資訊,請參閱 類別 Convert 。 如需當目的地類型可以儲存來源類型值但不足以儲存特定來源值時所發生的錯誤,請參閱 OverflowException 例外狀況。
注意
在許多情況下,您的語言編譯器會偵測到來源類型與目標型別之間沒有轉換,併發出編譯器錯誤。
下列各節將討論嘗試轉換擲回 InvalidCastException 例外狀況的一些條件:
若要讓明確參考轉換成功,來源值必須是 null
,或者來源引數所參考的物件類型必須可透過隱含參考轉換轉換成目的地類型。
下列中繼語言 (IL) 指令擲回 InvalidCastException 例外狀況:
castclass
refanyval
unbox
InvalidCastException 會使用 HRESULT COR_E_INVALIDCAST,其值為 0x80004002。
如需執行個體的初始屬性值的清單InvalidCastException,請參閱InvalidCastException建構函式。
基本型別和 IConvertible
您直接或間接呼叫不支援特定轉換的基本類型實作 IConvertible 。 例如,嘗試將 Boolean 值轉換成 或 DateTime 將 值轉換為 擲 Int32 回 InvalidCastException 例外狀況。 Char 下列範例會呼叫 和 Convert.ToChar(Boolean) 方法, Boolean.IConvertible.ToChar 將值 Char 轉換成 Boolean 。 在這兩種情況下,方法呼叫都會 InvalidCastException 擲回例外狀況。
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.
open System
let flag = true
try
let conv: IConvertible = flag
let ch = conv.ToChar null
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Cannot convert a Boolean to a Char."
try
let ch = Convert.ToChar flag
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "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.
因為不支援轉換,所以沒有因應措施。
Convert.ChangeType 方法
您已呼叫 方法, Convert.ChangeType 將物件從某個類型轉換成另一個類型,但其中一個或兩種類型都未實作 IConvertible 介面。
在大部分情況下,因為不支援轉換,所以沒有因應措施。 在某些情況下,可能的因應措施是從來源類型將屬性值手動指派給目標型別的類似屬性。
縮小轉換和 IConvertible 實作
縮小運算子會定義型別所支援的明確轉換。 如果 Option Strict
位於) 上,則為 C# 中的轉換運算子或 CType
Visual Basic (中的轉換方法,才能執行轉換。
不過,如果來源類型或目標型別都未定義兩種類型之間的明確或縮小轉換,而 IConvertible 一或兩種類型的實作不支援從來源類型轉換為目標型別, InvalidCastException 則會擲回例外狀況。
在大部分情況下,因為不支援轉換,所以沒有因應措施。
下播
您正在向下傳播,也就是嘗試將基底類型的實例轉換成其其中一個衍生類型。 在下列範例中,嘗試將 物件 PersonWithID
轉換成 Person
物件會失敗。
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.
open System
type Person() =
member val Name = String.Empty with get, set
type PersonWithId() =
inherit Person()
member val Id = String.Empty with get, set
let p = Person()
p.Name <- "John"
try
let pid = p :?> PersonWithId
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Conversion failed."
let pid1 = PersonWithId()
pid1.Name <- "John"
pid1.Id <- "246"
let p1: Person = pid1
try
let pid1a = p1 :?> PersonWithId
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Conversion failed."
// The example displays the following output:
// Conversion failed.
// 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
物件從 物件到 物件 Person
建立物件時,或物件為 null
時, Person
下播 PersonWithId
才會成功。
從介面物件轉換
您嘗試將介面物件轉換成實作該介面的類型,但目標型別與原本衍生介面物件之型別的型別或基類不同。 下列範例 InvalidCastException 會在嘗試將 物件轉換成 IFormatProvider 物件 DateTimeFormatInfo 時擲回例外狀況。 轉換失敗, DateTimeFormatInfo 因為雖然 類別會實作 IFormatProvider 介面, DateTimeFormatInfo 但物件與衍生介面物件的類別無關 CultureInfo 。
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()
open System
open System.Globalization
let culture = CultureInfo.InvariantCulture
let provider: IFormatProvider = culture
let dt = provider :?> DateTimeFormatInfo
// 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 。 如果介面物件轉換成原始型別基底類型的實例,轉換也會成功。
字串轉換
您嘗試使用 C# 中的轉型運算子,將值或物件轉換成其字串表示。 在下列範例中,嘗試將值轉換成 Char 字串,以及嘗試將整數轉換成字串會擲回 InvalidCastException 例外狀況。
using System;
public class Example
{
public static void Main()
{
object value = 12;
// Cast throws an InvalidCastException exception.
string s = (string) value;
}
}
let value: obj = 12
// Cast throws an InvalidCastException exception.
let s = value :?> string
注意
使用 Visual Basic CStr
運算子,將基本類型的值轉換為字串成功。 作業不會擲回例外狀況 InvalidCastException 。
若要成功將任何類型的實例轉換為其字串表示,請呼叫其 ToString
方法,如下列範例所示。 方法 ToString
一律存在,因為 ToString 方法是由 Object 類別所定義,因此會由所有 Managed 型別繼承或覆寫。
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
let value: obj = 12
let s = value.ToString()
printfn $"{s}"
// The example displays the following output:
// 12
Visual Basic 6.0 移轉
您正在升級 Visual Basic 6.0 應用程式,並呼叫使用者控制項中的自訂事件來Visual Basic .NET,並 InvalidCastException 擲回例外狀況並顯示訊息「指定的轉換無效」。 若要消除此例外狀況,請變更表單中的程式程式碼 (,例如 Form1
)
Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5))
並將它取代為下列程式程式碼:
Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5))
建構函式
InvalidCastException() |
初始化 InvalidCastException 類別的新執行個體。 |
InvalidCastException(SerializationInfo, StreamingContext) |
使用序列化資料,初始化 InvalidCastException 類別的新執行個體。 |
InvalidCastException(String) |
使用指定的錯誤訊息,初始化 InvalidCastException 類別的新執行個體。 |
InvalidCastException(String, Exception) |
使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 InvalidCastException 類別的新執行個體。 |
InvalidCastException(String, Int32) |
使用指定的訊息和錯誤碼,初始化 InvalidCastException 類別的新執行個體。 |
屬性
Data |
取得鍵值組的集合,這些鍵值組會提供關於例外狀況的其他使用者定義資訊。 (繼承來源 Exception) |
HelpLink |
取得或設定與這個例外狀況相關聯的說明檔連結。 (繼承來源 Exception) |
HResult |
取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。 (繼承來源 Exception) |
InnerException |
取得造成目前例外狀況的 Exception 執行個體。 (繼承來源 Exception) |
Message |
取得描述目前例外狀況的訊息。 (繼承來源 Exception) |
Source |
取得或設定造成錯誤的應用程式或物件的名稱。 (繼承來源 Exception) |
StackTrace |
取得呼叫堆疊上即時運算框架的字串表示。 (繼承來源 Exception) |
TargetSite |
取得擲回目前例外狀況的方法。 (繼承來源 Exception) |
方法
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetBaseException() |
在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 Exception。 (繼承來源 Exception) |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfo。 (繼承來源 Exception) |
GetType() |
取得目前執行個體的執行階段類型。 (繼承來源 Exception) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
ToString() |
建立並傳回目前例外狀況的字串表示。 (繼承來源 Exception) |
事件
SerializeObjectState |
已過時。
當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。 (繼承來源 Exception) |