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 型のインスタンスから別の型への変換がサポートされていない場合、例外がスローされます。 例えばChar値をDateTime値にキャストしようとしたときにInvalidCastExceptionがスローされます。 OverflowExceptionは、キャストは正当なものですが、キャスト前の値がキャスト後の値の範囲外の場合にスローされる例外です。 InvalidCastException例外は開発者エラーによって発生し、ブロック内でtry/catch
処理しないでください。 代わりに、例外の原因を排除する必要があります。
システムでサポートされている変換については、Convertクラスを参照してください。 変換先の型がソース型の値を格納できるが、特定のソース値を格納するのに十分な大きさではない場合に発生するエラーについては、例外を OverflowException 参照してください。
注意
多くの場合、言語コンパイラは、ソース型とターゲット型の間に変換が存在しないことを検出し、コンパイラ エラーを発行します。
変換の試行によって例外がスロー InvalidCastException される条件の一部については、次のセクションで説明します。
- プリミティブ型と IConvertible
- Convert.ChangeType メソッド
- 縮小変換と IConvertible 実装
- ダウンキャスト
- インターフェイス オブジェクトからの変換
- 文字列変換
- Visual Basic 6.0 の移行
明示的な参照変換を成功させるには、ソース値を null
指定するか、ソース引数によって参照されるオブジェクト型を暗黙的な参照変換によって変換先の型に変換できる必要があります。
次の中間言語 (IL) 命令は例外を InvalidCastException スローします。
castclass
refanyval
unbox
InvalidCastException では、0x80004002値を持つ HRESULT COR_E_INVALIDCASTが使用されます。
インスタンスの初期プロパティ値の一覧についてはInvalidCastExceptionを参照してください、InvalidCastExceptionコンス トラクター。
プリミティブ型と IConvertible
特定の変換をサポートしていないプリミティブ型の IConvertible 実装を直接または間接的に呼び出します。 たとえば、値を a Char またはInt32DateTime値に変換Booleanしようとすると、例外がInvalidCastExceptionスローされます。 次の例では、メソッドとConvert.ToChar(Boolean)メソッドの両方をBoolean.IConvertible.ToChar呼び出して値を Boolean .Char どちらの場合も、メソッド呼び出しは例外を 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 実装
縮小演算子は、型でサポートされる明示的な変換を定義します。 変換を実行するには、C# のキャスト演算子または CType
Visual Basic の変換メソッド (オンの場合Option Strict
) が必要です。
ただし、ソース型とターゲット型の両方が 2 つの型間の明示的または縮小変換を定義せず、 IConvertible 一方または両方の型の実装でソース型からターゲット型への変換がサポートされていない場合は、 InvalidCastException 例外がスローされます。
ほとんどの場合、変換がサポートされていないため回避策はありません。
ダウンキャスト
つまり、基本型のインスタンスを派生型のいずれかに変換しようとしています。 次の例では、オブジェクトを Person
オブジェクトに PersonWithID
変換しようとすると失敗します。
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
は、オブジェクトから PersonWithId
オブジェクトへの Person
アップキャストによってオブジェクトが作成された場合、またはオブジェクトが Person
null
.
インターフェイス オブジェクトからの変換
インターフェイス オブジェクトを、そのインターフェイスを実装する型に変換しようとしていますが、ターゲットの型が、インターフェイス オブジェクトの派生元の型と同じ型または基底クラスではありません。 次の例では、オブジェクトをInvalidCastExceptionオブジェクトに変換しようとしたときに例外をIFormatProviderDateTimeFormatInfoスローします。 このクラスはインターフェイスを 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 BasicCStr
演算子を使用してプリミティブ型の値を文字列に変換すると成功します。 この操作では例外はスロー InvalidCastException されません。
任意の型のインスタンスを文字列形式に正常に変換するには、次の例のようにメソッドを呼び出します ToString
。 メソッドはToString
クラスによって定義されるため、すべてのマネージド型によってObject継承またはオーバーライドされるためToString、メソッドは常に存在します。
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 の移行
ユーザー コントロールのカスタム イベントを呼び出して .NET をVisual BasicするVisual Basic 6.0 アプリケーションをアップグレードするとInvalidCastException、"Specified cast is not valid" というメッセージで例外がスローされます。 この例外を排除するには、フォームのコード行を変更します (例 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() |
派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の根本原因である Exception を返します。 (継承元 Exception) |
GetHashCode() |
既定のハッシュ関数として機能します。 (継承元 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。 (継承元 Exception) |
GetType() |
現在のインスタンスのランタイム型を取得します。 (継承元 Exception) |
MemberwiseClone() |
現在の Object の簡易コピーを作成します。 (継承元 Object) |
ToString() |
現在の例外の文字列形式を作成して返します。 (継承元 Exception) |
events
SerializeObjectState |
互換性のために残されています。
例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。 (継承元 Exception) |