InvalidCastException 클래스

정의

잘못된 캐스팅 또는 명시적 변환에 대해 throw되는 예외입니다.

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 형식 변환을 참조하세요.

InvalidCastException 한 형식의 인스턴스를 다른 형식으로 변환할 수 없는 경우 예외가 throw됩니다. 예를 들어 값을 값 DateTime 으로 Char 변환하려고 시도하면 예외가 InvalidCastException throw됩니다. 한 형식에서 다른 형식으로의 변환이 지원되는 경우 throw되는 예외와 다르 OverflowException 지만 원본 형식의 값이 대상 형식의 범위를 벗어났습니다. InvalidCastException 예외는 개발자 오류로 인해 발생하며 블록에서 try/catch 처리해서는 안 됩니다. 대신 예외의 원인을 제거해야 합니다.

시스템에서 지원하는 변환에 대한 자세한 내용은 클래스를 참조하세요 Convert . 대상 형식이 원본 형식 값을 저장할 수 있지만 특정 소스 값을 저장할 만큼 크지 않을 때 발생하는 오류는 예외를 OverflowException 참조하세요.

참고

대부분의 경우 언어 컴파일러는 원본 형식과 대상 형식 간에 변환이 없음을 감지하고 컴파일러 오류를 발생합니다.

변환 시도에서 예외를 throw InvalidCastException 하는 조건 중 일부는 다음 섹션에서 설명합니다.

명시적 참조 변환에 성공하려면 원본 값이어야 null합니다. 또는 소스 인수에서 참조하는 개체 형식을 암시적 참조 변환을 통해 대상 형식으로 변환할 수 있어야 합니다.

다음 IL(중간 언어) 지침은 예외를 InvalidCastException throw합니다.

  • castclass

  • refanyval

  • unbox

InvalidCastException 는 값이 0x80004002 HRESULT COR_E_INVALIDCAST 사용합니다.

인스턴스의 초기 속성 값의 목록을 InvalidCastException, 참조는 InvalidCastException 생성자입니다.

기본 형식 및 IConvertible

특정 변환을 지원하지 않는 기본 형식의 IConvertible 구현을 직접 또는 간접적으로 호출합니다. 예를 들어 값을 a Char 또는 Int32 DateTime 값으로 Boolean 변환하려고 하면 예외가 InvalidCastException throw됩니다. 다음 예제에서는 값을 Char변환하기 위해 메서드와 Convert.ToChar(Boolean) 메서드를 Boolean 모두 Boolean.IConvertible.ToChar 호출합니다. 두 경우 모두 메서드 호출은 예외를 InvalidCastException throw합니다.

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)의 변환 메서드가 필요합니다.

그러나 원본 형식이나 대상 형식이 두 형식 간의 명시적 또는 축소 변환을 정의하지 않고 하나 또는 두 형식 IConvertible 의 구현이 원본 형식에서 대상 형식 InvalidCastException 으로의 변환을 지원하지 않는 경우 예외가 throw됩니다.

대부분의 경우 변환이 지원되지 않으므로 해결 방법이 없습니다.

다운캐스팅

즉, 기본 형식의 인스턴스를 파생 형식 중 하나로 변환하려고 다운캐스트하고 있습니다. 다음 예제에서는 개체를 개체 PersonWithIDPerson 변환하려고 하면 실패합니다.

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 인 경우에만 다운캐스트 PersonWithIdPerson null성공합니다.

인터페이스 개체에서 변환

인터페이스 개체를 해당 인터페이스를 구현하는 형식으로 변환하려고 하지만 대상 형식은 인터페이스 개체가 원래 파생된 형식의 동일한 형식 또는 기본 클래스가 아닙니다. 다음 예제에서는 개체를 InvalidCastException 개체로 변환하려고 할 때 예외를 IFormatProvider DateTimeFormatInfo throw합니다. 클래스가 인터페이스를 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 throw합니다.

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 throw하지 않습니다.

모든 형식의 인스턴스를 해당 문자열 표현으로 성공적으로 변환하려면 다음 예제와 같이 해당 ToString 메서드를 호출합니다. 메서드가 ToString 클래스에 ToString 의해 Object 정의되므로 모든 관리되는 형식에서 상속되거나 재정의되므로 메서드는 항상 존재합니다.

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)

serialize된 데이터를 사용하여 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

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 예외에 대한 문자열 표현을 만들고 반환합니다.

(다음에서 상속됨 Exception)

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

추가 정보