Convert.ChangeType Convert.ChangeType Convert.ChangeType Convert.ChangeType Method

정의

값이 지정된 개체와 동일한 지정된 형식의 개체를 반환합니다.Returns an object of a specified type whose value is equivalent to a specified object.

오버로드

ChangeType(Object, Type) ChangeType(Object, Type) ChangeType(Object, Type) ChangeType(Object, Type)

값이 지정된 개체와 동일한 지정된 형식의 개체를 반환합니다.Returns an object of the specified type and whose value is equivalent to the specified object.

ChangeType(Object, TypeCode) ChangeType(Object, TypeCode) ChangeType(Object, TypeCode)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object.

ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object. 매개 변수에서 문화권별 서식 지정 정보를 제공합니다.A parameter supplies culture-specific formatting information.

ChangeType(Object, TypeCode, IFormatProvider) ChangeType(Object, TypeCode, IFormatProvider) ChangeType(Object, TypeCode, IFormatProvider)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object. 매개 변수에서 문화권별 서식 지정 정보를 제공합니다.A parameter supplies culture-specific formatting information.

ChangeType(Object, Type) ChangeType(Object, Type) ChangeType(Object, Type) ChangeType(Object, Type)

값이 지정된 개체와 동일한 지정된 형식의 개체를 반환합니다.Returns an object of the specified type and whose value is equivalent to the specified object.

public:
 static System::Object ^ ChangeType(System::Object ^ value, Type ^ conversionType);
public static object ChangeType (object value, Type conversionType);
static member ChangeType : obj * Type -> obj
Public Shared Function ChangeType (value As Object, conversionType As Type) As Object

매개 변수

value
Object Object Object Object

IConvertible 인터페이스를 구현하는 개체An object that implements the IConvertible interface.

conversionType
Type Type Type Type

반환할 개체의 형식입니다.The type of object to return.

반환

형식이 conversionType이고 값이 value와 동일한 개체입니다.An object whose type is conversionType and whose value is equivalent to value.

또는-or- Nothingvalue이고 null이 값 형식이 아닌 경우 null 참조입니다(Visual Basic의 경우 conversionType).A null reference (Nothing in Visual Basic), if value is null and conversionType is not a value type.

예외

이 변환은 지원되지 않습니다.This conversion is not supported.

또는-or- valuenull이고 conversionType이 값 형식입니다.value is null and conversionType is a value type.

또는-or- valueIConvertible 인터페이스를 구현하지 않습니다.value does not implement the IConvertible interface.

valueconversionType에서 인식되는 형식이 아닙니다.value is not in a format recognized by conversionType.

valueconversionType 형식의 범위를 벗어나는 숫자를 나타냅니다.value represents a number that is out of the range of conversionType.

conversionTypenull인 경우conversionType is null.

예제

다음 예제에서는 ChangeType 메서드를 사용하는 방법을 보여 줍니다.The following example illustrates the use of the ChangeType method.

using namespace System;

int main()
{
   Double d = -2.345;
   int i =  *safe_cast<Int32^>(Convert::ChangeType( d, int::typeid ));
   Console::WriteLine( "The double value {0} when converted to an int becomes {1}", d, i );
   String^ s = "12/12/98";
   DateTime dt =  *safe_cast<DateTime^>(Convert::ChangeType( s, DateTime::typeid ));
   Console::WriteLine( "The string value {0} when converted to a Date becomes {1}", s, dt );
}
using System;

public class ChangeTypeTest {
    public static void Main() {

        Double d = -2.345;
        int i = (int)Convert.ChangeType(d, typeof(int));

        Console.WriteLine("The double value {0} when converted to an int becomes {1}", d, i);

        string s = "12/12/98";
        DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

        Console.WriteLine("The string value {0} when converted to a Date becomes {1}", s, dt);        
    }
}
Public Class ChangeTypeTest
    
    Public Shared Sub Main()
        Dim d As [Double] = - 2.345
        Dim i As Integer = CInt(Convert.ChangeType(d, GetType(Integer)))
        
        Console.WriteLine("The double value {0} when converted to an int becomes {1}", d, i)
        Dim s As String = "12/12/98"
        Dim dt As DateTime = CType(Convert.ChangeType(s, GetType(DateTime)), DateTime)
        
        Console.WriteLine("The string value {0} when converted to a Date becomes {1}", s, dt)
    End Sub
End Class 'ChangeTypeTest

설명

ChangeType 지정한 개체를 변환 하는 범용 변환 메서드는 valueconversionType입니다.ChangeType is a general-purpose conversion method that converts the object specified by value to conversionType. 합니다 value 매개 변수는 모든 형식의 개체 수 및 conversionType 수도 있습니다는 Type 모든 기본 또는 사용자 지정 형식을 나타내는 개체입니다.The value parameter can be an object of any type, and conversionType can also be a Type object that represents any base or custom type. 변환이 성공 하기 value 구현 해야 합니다 IConvertible 메서드는 단순히 적절 한 호출을 래핑한 때문 IConvertible 메서드.For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. 메서드를 사용 하려면 해당 변환 valueconversionType 지원 합니다.The method requires that conversion of value to conversionType be supported.

이 메서드는 변환에 대 한 현재 스레드의 문화권을 사용합니다.This method uses the current thread's culture for the conversion.

호출자 참고

ChangeType(Object, Type) 메서드는 다른 형식으로 열거형 값을 변환할 수 있습니다.The ChangeType(Object, Type) method can convert an enumeration value to another type. 그러나 변환할 수 없는 다른 형식 열거형 값을 소스 형식 열거형의 기본 형식인 경우에 합니다.However, it cannot convert another type to an enumeration value, even if the source type is the underlying type of the enumeration. 열거형 값을 형식으로 변환 하려면 (C#에서)에 캐스팅 연산자나 변환 함수 (Visual Basic)를 사용 합니다.To convert a type to an enumeration value, use a casting operator (in C#) or a conversion function (in Visual Basic). 다음 예제에서는 변환 된 대륙 열거형 값입니다.The following example illustrates the conversion to and from a Continent enumeration value.

[! 코드 csharpSystem.Convert.ChangeType#5] [! 코드 vbSystem.Convert.ChangeType#5][!code-csharpSystem.Convert.ChangeType#5] [!code-vbSystem.Convert.ChangeType#5] ChangeType(Object, Type) 메서드 다른 형식으로 null 허용 형식을 변환할 수 있습니다.The ChangeType(Object, Type) method can convert a nullable type to another type. 그러나 다른 형식을 nullable 형식의 값으로 변환할 수 없습니다 경우에 conversionType 의 기본 형식인는 Nullable<T>합니다. 변환을 수행 하려면 (C#에서)에 캐스팅 연산자나 변환 함수 (Visual Basic)를 사용할 수 있습니다.However, it cannot convert another type to a value of a nullable type, even if conversionType is the underlying type of the Nullable<T>.To perform the conversion, you can use a casting operator (in C#) or a conversion function (in Visual Basic). 다음 예제에서는 nullable 형식 간의 변환을 보여 줍니다.The following example illustrates the conversion to and from a nullable type.

[! 코드 csharpSystem.Convert.ChangeType#7] [! 코드 vbSystem.Convert.ChangeType#7][!code-csharpSystem.Convert.ChangeType#7] [!code-vbSystem.Convert.ChangeType#7]

ChangeType(Object, TypeCode) ChangeType(Object, TypeCode) ChangeType(Object, TypeCode)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object.

public:
 static System::Object ^ ChangeType(System::Object ^ value, TypeCode typeCode);
public static object ChangeType (object value, TypeCode typeCode);
static member ChangeType : obj * TypeCode -> obj

매개 변수

value
Object Object Object Object

IConvertible 인터페이스를 구현하는 개체An object that implements the IConvertible interface.

typeCode
TypeCode TypeCode TypeCode TypeCode

반환할 개체의 형식입니다.The type of object to return.

반환

내부 형식이 typeCode이고 값이 value와 동일한 개체입니다.An object whose underlying type is typeCode and whose value is equivalent to value.

또는-or- Nothingvalue이고 nulltypeCode, Empty 또는 String이면 null 참조(Visual Basic의 경우 Object)입니다.A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

예외

이 변환은 지원되지 않습니다.This conversion is not supported.

또는-or- valuenulltypeCode가 값 형식을 지정합니다.value is null and typeCode specifies a value type.

또는-or- valueIConvertible 인터페이스를 구현하지 않습니다.value does not implement the IConvertible interface.

valuetypeCode 형식에서 인식하는 형식이 아닙니다.value is not in a format recognized by the typeCode type.

valuetypeCode 형식의 범위를 벗어나는 숫자를 나타냅니다.value represents a number that is out of the range of the typeCode type.

typeCode이 잘못되었습니다.typeCode is invalid.

예제

다음 예제를 사용 하는 방법을 합니다 ChangeType(Object, TypeCode) 변경 하는 방법은 Object 에 지정 된 형식에는 TypeCode 매개 변수, 가능한 경우.The following example illustrates how to use the ChangeType(Object, TypeCode) method to change an Object to the type specified by the TypeCode parameter, if possible.

using namespace System;

void main()
{
   Double d = -2.345;
   int i = (int) Convert::ChangeType(d, TypeCode::Int32);

   Console::WriteLine("The Double {0} when converted to an Int32 is {1}", d, i);

   String^ s = "12/12/2009";
   DateTime dt = (DateTime)Convert::ChangeType(s, DateTime::typeid);

   Console::WriteLine("The String {0} when converted to a Date is {1}", s, dt);        
}
// The example displays the following output:
//    The Double -2.345 when converted to an Int32 is -2
//    The String 12/12/2009 when converted to a Date is 12/12/2009 12:00:00 AM
using System;

public class ChangeTypeTest {
    public static void Main() {

        Double d = -2.345;
        int i = (int)Convert.ChangeType(d, TypeCode.Int32);

        Console.WriteLine("The Double {0} when converted to an Int32 is {1}", d, i);

        string s = "12/12/2009";
        DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

        Console.WriteLine("The String {0} when converted to a Date is {1}", s, dt);        
    }
}
// The example displays the following output:
//    The Double -2.345 when converted to an Int32 is -2
//    The String 12/12/2009 when converted to a Date is 12/12/2009 12:00:00 AM
Public Class ChangeTypeTest
    
    Public Shared Sub Main()
        Dim d As [Double] = - 2.345
        Dim i As Integer = CInt(Convert.ChangeType(d, TypeCode.Int32))
        
        Console.WriteLine("The Double {0} when converted to an Int32 is {1}", d, i)
        Dim s As String = "12/12/2009"
        Dim dt As DateTime = CDate(Convert.ChangeType(s, TypeCode.DateTime))
        
        Console.WriteLine("The String {0} when converted to a Date is {1}", s, dt)
    End Sub 
End Class 
' The example displays the following output:
'    The Double -2.345 when converted to an Int32 is -2
'    The String 12/12/2009 when converted to a Date is 12/12/2009 12:00:00 AM

설명

ChangeType(Object, TypeCode) 지정한 개체를 변환 하는 범용 변환 메서드는 value 미리 정의 된 형식으로 지정 된 typeCode합니다.ChangeType(Object, TypeCode) is a general-purpose conversion method that converts the object specified by value to a predefined type specified by typeCode. value 매개 변수는 모든 형식의 개체를 수 있습니다.The value parameter can be an object of any type. 변환이 성공 하기 value 구현 해야 합니다 IConvertible 메서드는 단순히 적절 한 호출을 래핑한 때문 IConvertible 메서드.For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. 메서드는 변환 해야 valuetypeCode 지원 합니다.The method also requires that conversion of value to typeCode be supported.

합니다 ChangeType(Object, TypeCode) 메서드의 변환을 지원 하지 않습니다 value 사용자 지정 형식입니다.The ChangeType(Object, TypeCode) method does not support the conversion of value to a custom type. 이러한 변환은 수행 하려면 호출을 ChangeType(Object, Type) 메서드.To perform such a conversion, call the ChangeType(Object, Type) method.

ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider) ChangeType(Object, Type, IFormatProvider)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object. 매개 변수에서 문화권별 서식 지정 정보를 제공합니다.A parameter supplies culture-specific formatting information.

public:
 static System::Object ^ ChangeType(System::Object ^ value, Type ^ conversionType, IFormatProvider ^ provider);
public static object ChangeType (object value, Type conversionType, IFormatProvider provider);
static member ChangeType : obj * Type * IFormatProvider -> obj
Public Shared Function ChangeType (value As Object, conversionType As Type, provider As IFormatProvider) As Object

매개 변수

value
Object Object Object Object

IConvertible 인터페이스를 구현하는 개체An object that implements the IConvertible interface.

conversionType
Type Type Type Type

반환할 개체의 형식입니다.The type of object to return.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

문화권별 서식 지정 정보를 제공하는 개체입니다.An object that supplies culture-specific formatting information.

반환

형식이 conversionType이고 값이 value와 동일한 개체입니다.An object whose type is conversionType and whose value is equivalent to value.

또는-or- valueTypevalue이 같으면 conversionType를 반환합니다.value, if the Type of value and conversionType are equal.

또는-or- Nothingvalue이고 null이 값 형식이 아닌 경우 null 참조입니다(Visual Basic의 경우 conversionType).A null reference (Nothing in Visual Basic), if value is null and conversionType is not a value type.

예외

이 변환은 지원되지 않습니다.This conversion is not supported.

또는-or- valuenull이고 conversionType이 값 형식입니다.value is null and conversionType is a value type.

또는-or- valueIConvertible 인터페이스를 구현하지 않습니다.value does not implement the IConvertible interface.

valueconversionType에서 인식되는 provider의 형식이 아닌 경우value is not in a format for conversionType recognized by provider.

valueconversionType형식의 범위를 벗어나는 숫자를 나타냅니다.value represents a number that is out of the range of conversionType.

conversionTypenull입니다.conversionType is null.

예제

다음 예제에서는 Temperature 인터페이스를 구현하는 IConvertible 클래스를 정의합니다.The following example defines a Temperature class that implements the IConvertible interface.

using namespace System;
using namespace System::Globalization;

public ref class Temperature : IConvertible
{
private:
   Decimal m_Temp;

public:
   Temperature(Decimal temperature)
   {
      m_Temp = temperature;
   }
   
   property Decimal Celsius {
      Decimal get() { return m_Temp; }
   }
   
   property Decimal Kelvin {
      Decimal get() { return m_Temp + (Decimal) 273.15; }
   }
   
   property Decimal Fahrenheit {
      Decimal get() { return Math::Round((Decimal) (m_Temp * 9 / 5 + 32), 2); }
   }
   
   virtual String^ ToString()
   override {
      return m_Temp.ToString("N2") + "�C";
   }

   // IConvertible implementations.
   virtual TypeCode GetTypeCode()
   {
      return TypeCode::Object;
   }
   
   virtual bool ToBoolean(IFormatProvider^ provider) 
   {
      if (m_Temp == 0)
         return false;
      else
         return true;
   } 
   
   virtual Byte ToByte(IFormatProvider^ provider)
   {
      if (m_Temp < Byte::MinValue || m_Temp > Byte::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the Byte type.", 
                                                   m_Temp));
      else
         return Decimal::ToByte(m_Temp);
   }
   
   virtual Char ToChar(IFormatProvider^ provider)
   {
      throw gcnew InvalidCastException("Temperature to Char conversion is not supported.");
   } 
   
   virtual DateTime ToDateTime(IFormatProvider^ provider)
   {
      throw gcnew InvalidCastException("Temperature to DateTime conversion is not supported.");
   }
   
   virtual Decimal ToDecimal(IFormatProvider^ provider)
   {
      return m_Temp;
   }
   
   virtual Double ToDouble(IFormatProvider^ provider)
   {
      return Decimal::ToDouble(m_Temp);
   }   
   
   virtual Int16 ToInt16(IFormatProvider^ provider)
   {
      if (m_Temp < Int16::MinValue || m_Temp > Int16::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the Int16 type.",
                                                   m_Temp));
      else
         return Decimal::ToInt16(m_Temp);
   }
   
   virtual Int32 ToInt32(IFormatProvider^ provider)
      {
      if (m_Temp < Int32::MinValue || m_Temp > Int32::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the Int32 type.",
                                                   m_Temp));
      else
         return Decimal::ToInt32(m_Temp);
   }
   
   virtual Int64 ToInt64(IFormatProvider^ provider)
   {
      if (m_Temp < Int64::MinValue || m_Temp > Int64::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the Int64 type.",
                                                   m_Temp));
      else
         return Decimal::ToInt64(m_Temp);
   }
   
   virtual SByte ToSByte(IFormatProvider^ provider)
   {
      if (m_Temp < SByte::MinValue || m_Temp > SByte::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the SByte type.",
                                                   m_Temp));
      else
         return Decimal::ToSByte(m_Temp);
   }

   virtual Single ToSingle(IFormatProvider^ provider)
   {
      return Decimal::ToSingle(m_Temp);
   }

   virtual String^ ToString(IFormatProvider^ provider)
   {
      return m_Temp.ToString("N2", provider) + "�C";
   }
   
   virtual Object^ ToType(Type^ conversionType, IFormatProvider^ provider)
   {
      switch (Type::GetTypeCode(conversionType))
      {
      case TypeCode::Boolean: 
            return ToBoolean(nullptr);
      case TypeCode::Byte:
            return ToByte(nullptr);
      case TypeCode::Char:
            return ToChar(nullptr);
      case TypeCode::DateTime:
            return ToDateTime(nullptr);
      case TypeCode::Decimal:
            return ToDecimal(nullptr);
      case TypeCode::Double:
            return ToDouble(nullptr);
      case TypeCode::Int16:
            return ToInt16(nullptr);
      case TypeCode::Int32:
            return ToInt32(nullptr);
      case TypeCode::Int64:
            return ToInt64(nullptr);
      case TypeCode::Object:
            if (Temperature::typeid->Equals(conversionType))
               return this;
            else
               throw gcnew InvalidCastException(String::Format("Conversion to a {0} is not supported.",
                                                            conversionType->Name));
      case TypeCode::SByte:
            return ToSByte(nullptr);
      case TypeCode::Single:
            return ToSingle(nullptr);
      case TypeCode::String:
            return ToString(provider);
      case TypeCode::UInt16:
            return ToUInt16(nullptr);
      case TypeCode::UInt32:
            return ToUInt32(nullptr);
      case TypeCode::UInt64:
            return ToUInt64(nullptr);   
         default:
            throw gcnew InvalidCastException(String::Format("Conversion to {0} is not supported.", conversionType->Name));   
      }
   }
   
   virtual UInt16 ToUInt16(IFormatProvider^ provider)
   {
      if (m_Temp < UInt16::MinValue || m_Temp > UInt16::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the UInt16 type.",
                                                   m_Temp));
      else
         return Decimal::ToUInt16(m_Temp);
   }

   virtual UInt32 ToUInt32(IFormatProvider^ provider)
   {
      if (m_Temp < UInt32::MinValue || m_Temp > UInt32::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the UInt32 type.",
                                                   m_Temp));
      else
         return Decimal::ToUInt32(m_Temp);
   }
   
   virtual UInt64 ToUInt64(IFormatProvider^ provider)
   {
      if (m_Temp < UInt64::MinValue || m_Temp > UInt64::MaxValue)
         throw gcnew OverflowException(String::Format("{0} is out of range of the UInt64 type.",
                                                   m_Temp));
      else
         return Decimal::ToUInt64(m_Temp);
   }
};
using System;
using System.Globalization;

public class Temperature : IConvertible
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }
   
   public decimal Celsius
   {
      get { return this.m_Temp; }   
   }
   
   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }    
   }
   
   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) (this.m_Temp * 9 / 5 + 32), 2); }
   }
   
   public override string ToString()
   {
      return m_Temp.ToString("N2") + "°C";
   }

   // IConvertible implementations.
   public TypeCode GetTypeCode()
   {
      return TypeCode.Object;
   }
   
   public bool ToBoolean(IFormatProvider provider) 
   {
      if (m_Temp == 0)
         return false;
      else
         return true;
   } 
   
   public byte ToByte(IFormatProvider provider)
   {
      if (m_Temp < Byte.MinValue || m_Temp > Byte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.", 
                                                   this.m_Temp));
      else
         return Decimal.ToByte(this.m_Temp);
   }
   
   public char ToChar(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to Char conversion is not supported.");
   } 
   
   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to DateTime conversion is not supported.");
   }
   
   public decimal ToDecimal(IFormatProvider provider)
   {
      return this.m_Temp;
   }
   
   public double ToDouble(IFormatProvider provider)
   {
      return Decimal.ToDouble(this.m_Temp);
   }   
   
   public short ToInt16(IFormatProvider provider)
   {
      if (this.m_Temp < Int16.MinValue || this.m_Temp > Int16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt16(this.m_Temp);
   }
   
   public int ToInt32(IFormatProvider provider)
      {
      if (this.m_Temp < Int32.MinValue || this.m_Temp > Int32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt32(this.m_Temp);
   }
   
   public long ToInt64(IFormatProvider provider)
   {
      if (this.m_Temp < Int64.MinValue || this.m_Temp > Int64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt64(this.m_Temp);
   }
   
   public sbyte ToSByte(IFormatProvider provider)
   {
      if (this.m_Temp < SByte.MinValue || this.m_Temp > SByte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the SByte type.",
                                                   this.m_Temp));
      else
         return Decimal.ToSByte(this.m_Temp);
   }

   public float ToSingle(IFormatProvider provider)
   {
      return Decimal.ToSingle(this.m_Temp);
   }

   public string ToString(IFormatProvider provider)
   {
      return m_Temp.ToString("N2", provider) + "°C";
   }
   
   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean: 
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(Temperature).Equals(conversionType))
               return this;
            else
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.",
                                                            conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(provider);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);   
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));   
      }
   }
   
   public ushort ToUInt16(IFormatProvider provider)
   {
      if (this.m_Temp < UInt16.MinValue || this.m_Temp > UInt16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt16(this.m_Temp);
   }

   public uint ToUInt32(IFormatProvider provider)
   {
      if (this.m_Temp < UInt32.MinValue || this.m_Temp > UInt32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt32(this.m_Temp);
   }
   
   public ulong ToUInt64(IFormatProvider provider)
   {
      if (this.m_Temp < UInt64.MinValue || this.m_Temp > UInt64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt64(this.m_Temp);
   }
}
Imports System.Globalization

Public Class Temperature : Implements IConvertible
   Private m_Temp As Decimal

   Public Sub New(temperature As Decimal)
      Me.m_Temp = temperature
   End Sub
   
   Public ReadOnly Property Celsius() As Decimal
      Get
         Return Me.m_Temp
      End Get   
   End Property
   
   Public ReadOnly Property Kelvin() As Decimal
      Get
         Return Me.m_Temp + 273.15d   
      End Get
   End Property
   
   Public ReadOnly Property Fahrenheit() As Decimal
      Get
         Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
      End Get      
   End Property
   
   Public Overrides Function ToString() As String
      Return m_Temp.ToString("N2") & "°C"
   End Function

   ' IConvertible implementations.
   Public Function GetTypeCode() As TypeCode _
                   Implements IConvertible.GetTypeCode
      Return TypeCode.Object
   End Function
   
   Public Function ToBoolean(provider As IFormatProvider) As Boolean _
                   Implements IConvertible.ToBoolean
      If m_Temp = 0 Then
         Return False
      Else
         Return True
      End If
   End Function 
   
   Public Function ToByte(provider As IFormatProvider) As Byte _
                   Implements IConvertible.ToByte
      If m_Temp < Byte.MinValue Or m_Temp > Byte.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Byte type.", _ 
                                                   Me.m_Temp)) 
      Else
         Return Decimal.ToByte(Me.m_Temp)
      End If       
   End Function
   
   Public Function ToChar(provider As IFormatProvider) As Char _
                   Implements IConvertible.ToChar
      Throw New InvalidCastException("Temperature to Char conversion is not supported.")
   End Function 
   
   Public Function ToDateTime(provider As IFormatProvider) As Date _
                   Implements IConvertible.ToDateTime
      Throw New InvalidCastException("Temperature to DateTime conversion is not supported.")
   End Function
   
   Public Function ToDecimal(provider As IFormatProvider) As Decimal _
                   Implements IConvertible.ToDecimal
      Return Me.m_Temp
   End Function
   
   Public Function ToDouble(provider As IFormatProvider) As Double _
                   Implements IConvertible.ToDouble
      Return Decimal.ToDouble(Me.m_Temp)
   End Function   
   
   Public Function ToInt16(provider As IFormatProvider) As Int16 _
                   Implements IConvertible.ToInt16
      If Me.m_Temp < Int16.MinValue Or Me.m_Temp > Int16.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int16 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt16(Me.m_Temp)   
      End If
   End Function
   
   Public Function ToInt32(provider As IFormatProvider) As Int32 _
                   Implements IConvertible.ToInt32
      If Me.m_Temp < Int32.MinValue Or Me.m_Temp > Int32.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int32 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt32(Me.m_Temp)
      End If      
   End Function
   
   Public Function ToInt64(provider As IFormatProvider) As Int64 _
                   Implements IConvertible.ToInt64
      If Me.m_Temp < Int64.MinValue Or Me.m_Temp > Int64.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the Int64 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToInt64(Me.m_Temp)
      End If      
   End Function
   
   Public Function ToSByte(provider As IFormatProvider) As SByte _
                   Implements IConvertible.ToSByte
      If Me.m_Temp < SByte.MinValue Or Me.m_Temp > SByte.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the SByte type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToSByte(Me.m_Temp)
      End If      
   End Function

   Public Function ToSingle(provider As IFormatProvider) As Single _
                   Implements IConvertible.ToSingle
      Return Decimal.ToSingle(Me.m_Temp)
   End Function

   Public Overloads Function ToString(provider As IFormatProvider) As String _
                   Implements IConvertible.ToString
      Return m_Temp.ToString("N2", provider) & "°C"
   End Function
   
   Public Function ToType(conversionType As Type, provider As IFormatProvider) As Object _
                   Implements IConvertible.ToType
      Select Case Type.GetTypeCode(conversionType)
         Case TypeCode.Boolean 
            Return Me.ToBoolean(Nothing)
         Case TypeCode.Byte
            Return Me.ToByte(Nothing)
         Case TypeCode.Char
            Return Me.ToChar(Nothing)
         Case TypeCode.DateTime
            Return Me.ToDateTime(Nothing)
         Case TypeCode.Decimal
            Return Me.ToDecimal(Nothing)
         Case TypeCode.Double
            Return Me.ToDouble(Nothing)
         Case TypeCode.Int16
            Return Me.ToInt16(Nothing)
         Case TypeCode.Int32
            Return Me.ToInt32(Nothing)
         Case TypeCode.Int64
            Return Me.ToInt64(Nothing)
         Case TypeCode.Object
            If GetType(Temperature).Equals(conversionType) Then
               Return Me
            Else
               Throw New InvalidCastException(String.Format("Conversion to a {0} is not supported.", _
                                                            conversionType.Name))
            End If 
         Case TypeCode.SByte
            Return Me.ToSByte(Nothing)
         Case TypeCode.Single
            Return Me.ToSingle(Nothing)
         Case TypeCode.String
            Return Me.ToString(provider)
         Case TypeCode.UInt16
            Return Me.ToUInt16(Nothing)
         Case TypeCode.UInt32
            Return Me.ToUInt32(Nothing)
         Case TypeCode.UInt64
            Return Me.ToUInt64(Nothing)   
         Case Else
            Throw New InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name))   
      End Select
   End Function
   
   Public Function ToUInt16(provider As IFormatProvider) As UInt16 _
                   Implements IConvertible.ToUInt16
      If Me.m_Temp < UInt16.MinValue Or Me.m_Temp > UInt16.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt16 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt16(Me.m_Temp)
      End If   
   End Function

   Public Function ToUInt32(provider As IFormatProvider) As UInt32 _
                   Implements IConvertible.ToUInt32
      If Me.m_Temp < UInt32.MinValue Or Me.m_Temp > UInt32.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt32 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt32(Me.m_Temp)
      End If   
   End Function
   
   Public Function ToUInt64(provider As IFormatProvider) As UInt64 _
                   Implements IConvertible.ToUInt64
      If Me.m_Temp < UInt64.MinValue Or Me.m_Temp > UInt64.MaxValue Then
         Throw New OverflowException(String.Format("{0} is out of range of the UInt64 type.", _
                                                   Me.m_Temp))
      Else
         Return Decimal.ToUInt64(Me.m_temp)
      End If   
   End Function
End Class

다음 예제에서는 인스턴스를 만듭니다는 Temperature 클래스 및 호출 합니다 ChangeType(Object, Type, IFormatProvider) 메서드 및.NET Framework에서 지원 되는 기본 숫자 형식으로 변환할 수는 String합니다.The following example creates an instance of the Temperature class and calls the ChangeType(Object, Type, IFormatProvider) method to convert it to the basic numeric types supported by the .NET Framework and to a String. 하는 방법을 보여 줍니다 합니다 ChangeType 메서드는 소스 형식에 대 한 호출을 래핑합니다 IConvertible 구현 합니다.It illustrates that the ChangeType method wraps a call to the source type's IConvertible implementation.

void main()
{     
   Temperature^ cool = gcnew Temperature(5);
   array<Type^>^ targetTypes = gcnew array<Type^> { SByte::typeid, Int16::typeid, Int32::typeid,
                                                    Int64::typeid, Byte::typeid, UInt16::typeid,
                                                    UInt32::typeid, UInt64::typeid, Decimal::typeid,
                                                    Single::typeid, Double::typeid, String::typeid };
   CultureInfo^ provider = gcnew CultureInfo("fr-FR");
      
   for each (Type^ targetType in targetTypes)
   {
      try {
         Object^ value = Convert::ChangeType(cool, targetType, provider);
         Console::WriteLine("Converted {0} {1} to {2} {3}.",
                           cool->GetType()->Name, cool->ToString(),
                           targetType->Name, value);
      }
      catch (InvalidCastException^) {
         Console::WriteLine("Unsupported {0} --> {1} conversion.",
                           cool->GetType()->Name, targetType->Name);
      }                     
      catch (OverflowException^) {
         Console::WriteLine("{0} is out of range of the {1} type.",
                           cool, targetType->Name);
      }
   }
}
// The example dosplays the following output:
//       Converted Temperature 5.00�C to SByte 5.
//       Converted Temperature 5.00�C to Int16 5.
//       Converted Temperature 5.00�C to Int32 5.
//       Converted Temperature 5.00�C to Int64 5.
//       Converted Temperature 5.00�C to Byte 5.
//       Converted Temperature 5.00�C to UInt16 5.
//       Converted Temperature 5.00�C to UInt32 5.
//       Converted Temperature 5.00�C to UInt64 5.
//       Converted Temperature 5.00�C to Decimal 5.
//       Converted Temperature 5.00�C to Single 5.
//       Converted Temperature 5.00�C to Double 5.
//       Converted Temperature 5.00�C to String 5,00�C.
public class Example
{
   public static void Main()
   {
      Temperature cool = new Temperature(5);
      Type[] targetTypes = { typeof(SByte), typeof(Int16), typeof(Int32),
                             typeof(Int64), typeof(Byte), typeof(UInt16),
                             typeof(UInt32), typeof(UInt64), typeof(Decimal),
                             typeof(Single), typeof(Double), typeof(String) };
      CultureInfo provider = new CultureInfo("fr-FR");
      
      foreach (Type targetType in targetTypes)
      {
         try {
            object value = Convert.ChangeType(cool, targetType, provider);
            Console.WriteLine("Converted {0} {1} to {2} {3}.",
                              cool.GetType().Name, cool.ToString(),
                              targetType.Name, value);
         }
         catch (InvalidCastException) {
            Console.WriteLine("Unsupported {0} --> {1} conversion.",
                              cool.GetType().Name, targetType.Name);
         }                     
         catch (OverflowException) {
            Console.WriteLine("{0} is out of range of the {1} type.",
                              cool, targetType.Name);
         }
      }
   }
}
// The example dosplays the following output:
//       Converted Temperature 5.00°C to SByte 5.
//       Converted Temperature 5.00°C to Int16 5.
//       Converted Temperature 5.00°C to Int32 5.
//       Converted Temperature 5.00°C to Int64 5.
//       Converted Temperature 5.00°C to Byte 5.
//       Converted Temperature 5.00°C to UInt16 5.
//       Converted Temperature 5.00°C to UInt32 5.
//       Converted Temperature 5.00°C to UInt64 5.
//       Converted Temperature 5.00°C to Decimal 5.
//       Converted Temperature 5.00°C to Single 5.
//       Converted Temperature 5.00°C to Double 5.
//       Converted Temperature 5.00°C to String 5,00°C.
Module Example
   Public Sub Main()
      Dim cool As New Temperature(5)
      Dim targetTypes() As Type = { GetType(SByte), GetType(Int16), GetType(Int32), _
                                    GetType(Int64), GetType(Byte), GetType(UInt16), _
                                    GetType(UInt32), GetType(UInt64), GetType(Decimal), _
                                    GetType(Single), GetType(Double), GetType(String) }
      Dim provider As New CultureInfo("fr-FR")
      
      For Each targetType As Type In targetTypes
         Try
            Dim value As Object = Convert.ChangeType(cool, targetType, provider)
            Console.WriteLine("Converted {0} {1} to {2} {3}.", _
                              cool.GetType().Name, cool.ToString(), _
                              targetType.Name, value)
         Catch e As InvalidCastException
            Console.WriteLine("Unsupported {0} --> {1} conversion.", _
                              cool.GetType().Name, targetType.Name)
         Catch e As OverflowException
            Console.WriteLine("{0} is out of range of the {1} type.", _
                              cool, targetType.Name)
         End Try                     
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted Temperature 5.00°C to SByte 5.
'       Converted Temperature 5.00°C to Int16 5.
'       Converted Temperature 5.00°C to Int32 5.
'       Converted Temperature 5.00°C to Int64 5.
'       Converted Temperature 5.00°C to Byte 5.
'       Converted Temperature 5.00°C to UInt16 5.
'       Converted Temperature 5.00°C to UInt32 5.
'       Converted Temperature 5.00°C to UInt64 5.
'       Converted Temperature 5.00°C to Decimal 5.
'       Converted Temperature 5.00°C to Single 5.
'       Converted Temperature 5.00°C to Double 5.
'       Converted Temperature 5.00°C to String 5,00°C.

설명

ChangeType 지정한 개체를 변환 하는 범용 변환 메서드는 valueconversionType입니다.ChangeType is a general-purpose conversion method that converts the object specified by value to conversionType. 합니다 value 매개 변수는 모든 형식의 개체 수 및 conversionType 수도 있습니다는 Type 모든 기본 또는 사용자 지정 형식을 나타내는 개체입니다.The value parameter can be an object of any type, and conversionType can also be a Type object that represents any base or custom type. 변환이 성공 하기 value 구현 해야 합니다 IConvertible 메서드는 단순히 적절 한 호출을 래핑한 때문 IConvertible 메서드.For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. 메서드를 사용 하려면 해당 변환 valueconversionType 지원 합니다.The method requires that conversion of value to conversionType be supported.

합니다 provider 매개 변수는는 IFormatProvider 변환에 대 한 서식 지정 정보를 제공 합니다.The provider parameter is an IFormatProvider implementation that supplies formatting information for the conversion. 기본 종속이 매개 변수는 사용 여부 및 방법을 IConvertible 구현 합니다.Whether and how this parameter is used depends on the underlying IConvertible implementation. 하는 경우 value 기본 데이터 형식인 provider 다음 변환에만 사용 됩니다.If value is a base data type, provider is used only for the following conversions:

  • 문자열, 숫자 또는 문자열을 숫자로 변환 합니다.Conversion from a number to a string, or from a string to a number. provider 이어야 합니다는 CultureInfo 개체를 NumberFormatInfo 개체 또는 사용자 지정 IFormatProvider 구현을 반환 하는 NumberFormatInfo 개체입니다.provider must be a CultureInfo object, a NumberFormatInfo object, or a custom IFormatProvider implementation that returns a NumberFormatInfo object. 그러나 때문에 ChangeType(Object, TypeCode, IFormatProvider) 메서드 기본 "G" 형식 지정자를 사용 하 여 변환을 수행 합니다 provider 매개 변수는 영향을 주지 않습니다 경우 value 대상 형식은 부호 없는 정수 또는 합니다.However, because the ChangeType(Object, TypeCode, IFormatProvider) method performs the conversion using the default "G" format specifier, the provider parameter has no effect if value or the target type is an unsigned integer. 하는 경우 provider 됩니다 nullCultureInfo 현재 스레드 문화권을 나타내는 개체를 사용 합니다.If provider is null, the CultureInfo object that represents the current thread culture is used.

  • 변환할을 DateTime 문자열로 또는 문자열에서 값을 DateTime 값입니다.Conversion from a DateTime value to a string, or from a string to a DateTime value. provider 이어야 합니다는 CultureInfo 또는 DateTimeFormatInfo 개체입니다.provider must be a CultureInfo or DateTimeFormatInfo object. 하는 경우 provider 됩니다 nullCultureInfo 현재 스레드 문화권을 나타내는 개체를 사용 합니다.If provider is null, the CultureInfo object that represents the current thread culture is used.

하는 경우 value 가 애플리케이션 정의 형식이 해당 IConvertible 구현을 사용할 수는 provider 매개 변수입니다.If value is an application-defined type, its IConvertible implementation may use the provider parameter.

호출자 참고

ChangeType(Object, Type, IFormatProvider) 메서드는 다른 형식으로 열거형 값을 변환할 수 있습니다.The ChangeType(Object, Type, IFormatProvider) method can convert an enumeration value to another type. 그러나 변환할 수 없는 다른 형식 열거형 값을 소스 형식 열거형의 기본 형식인 경우에 합니다.However, it cannot convert another type to an enumeration value, even if the source type is the underlying type of the enumeration. 열거형 값을 형식으로 변환 하려면 (C#에서)에 캐스팅 연산자나 변환 함수 (Visual Basic)를 사용 합니다.To convert a type to an enumeration value, use a casting operator (in C#) or a conversion function (in Visual Basic). 다음 예제에서는 변환 된 대륙 열거형 값입니다.The following example illustrates the conversion to and from a Continent enumeration value.

[! 코드 csharpSystem.Convert.ChangeType#5] [! 코드 vbSystem.Convert.ChangeType#5][!code-csharpSystem.Convert.ChangeType#5] [!code-vbSystem.Convert.ChangeType#5] ChangeType(Object, Type, IFormatProvider) 메서드 다른 형식으로 null 허용 형식을 변환할 수 있습니다.The ChangeType(Object, Type, IFormatProvider) method can convert a nullable type to another type. 그러나 다른 형식을 nullable 형식의 값으로 변환할 수 없습니다 경우에 conversionType 의 기본 형식인는 Nullable<T>합니다.However, it cannot convert another type to a value of a nullable type, even if conversionType is the underlying type of the Nullable<T>. 변환을 수행 하려면 (C#에서)에 캐스팅 연산자나 변환 함수 (Visual Basic)를 사용할 수 있습니다.To perform the conversion, you can use a casting operator (in C#) or a conversion function (in Visual Basic). 다음 예제에서는 nullable 형식 간의 변환을 보여 줍니다.The following example illustrates the conversion to and from a nullable type.

[! 코드 csharpSystem.Convert.ChangeType#8] [! 코드 vbSystem.Convert.ChangeType#8][!code-csharpSystem.Convert.ChangeType#8] [!code-vbSystem.Convert.ChangeType#8]

ChangeType(Object, TypeCode, IFormatProvider) ChangeType(Object, TypeCode, IFormatProvider) ChangeType(Object, TypeCode, IFormatProvider)

지정된 개체와 동일한 값을 갖는 지정된 형식의 개체를 반환합니다.Returns an object of the specified type whose value is equivalent to the specified object. 매개 변수에서 문화권별 서식 지정 정보를 제공합니다.A parameter supplies culture-specific formatting information.

public:
 static System::Object ^ ChangeType(System::Object ^ value, TypeCode typeCode, IFormatProvider ^ provider);
public static object ChangeType (object value, TypeCode typeCode, IFormatProvider provider);
static member ChangeType : obj * TypeCode * IFormatProvider -> obj

매개 변수

value
Object Object Object Object

IConvertible 인터페이스를 구현하는 개체An object that implements the IConvertible interface.

typeCode
TypeCode TypeCode TypeCode TypeCode

반환할 개체의 형식입니다.The type of object to return.

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

문화권별 서식 지정 정보를 제공하는 개체입니다.An object that supplies culture-specific formatting information.

반환

내부 형식이 typeCode이고 값이 value와 동일한 개체입니다.An object whose underlying type is typeCode and whose value is equivalent to value.

또는-or- Nothingvalue이고 nulltypeCode, Empty 또는 String이면 null 참조(Visual Basic의 경우 Object)입니다.A null reference (Nothing in Visual Basic), if value is null and typeCode is Empty, String, or Object.

예외

이 변환은 지원되지 않습니다.This conversion is not supported.

또는-or- valuenulltypeCode가 값 형식을 지정합니다.value is null and typeCode specifies a value type.

또는-or- valueIConvertible 인터페이스를 구현하지 않습니다.value does not implement the IConvertible interface.

valueprovider에서 인식되는 typeCode 형식에 대한 형식이 아닙니다.value is not in a format for the typeCode type recognized by provider.

valuetypeCode 형식의 범위를 벗어나는 숫자를 나타냅니다.value represents a number that is out of the range of the typeCode type.

typeCode이 잘못되었습니다.typeCode is invalid.

예제

다음 예제에서는 라는 사용자 지정 형식 공급자 정의 InterceptProvider 시기를 지정 하는 해당 GetFormat 메서드는 호출 되며 반환을 NumberFormatInfo FR-FR 문화권에 대 한 및 DateTimeFormatInfo EN-US 문화권에 대 한 개체입니다.The following example defines a custom format provider named InterceptProvider that indicates when its GetFormat method is called and returns a NumberFormatInfo for the fr-FR culture and a DateTimeFormatInfo object for the en-US culture. 이 형식 공급자에 대 한 모든 호출에서 되는 ChangeType(Object, TypeCode, IFormatProvider) 메서드.This format provider is used in all calls to the ChangeType(Object, TypeCode, IFormatProvider) method. 사용 하 여 배열을 만듭니다는 DoubleDateTime 값 및 호출을 반복된 합니다 ChangeType(Object, TypeCode, IFormatProvider) 각 값의 각 멤버와는 TypeCode 열거형입니다.The example then creates an array with a Double and a DateTime value and makes repeated calls to ChangeType(Object, TypeCode, IFormatProvider) with each value and each member of the TypeCode enumeration. 예제 메서드를 사용 하는 경우에 IFormatProvider 매개 변수에서는 또한를 사용 하 고는 provider 문화권 구분 서식 지정을 수행 하려면 매개 변수입니다.The example illustrates when the method uses the IFormatProvider parameter and also illustrates the use of the provider parameter to perform culture-sensitive formatting.

using namespace System;
using namespace System::Globalization;

ref class InterceptProvider : IFormatProvider
{
public: 
   virtual Object^ GetFormat(Type^ formatType) 
   {
      CultureInfo^ culture;
      if (formatType == NumberFormatInfo::typeid) {
         Console::WriteLine("   Returning a fr-FR numeric format provider.");
         
         culture = gcnew CultureInfo("fr-FR");
         return culture->NumberFormat;
      }  
      else if (formatType == DateTimeFormatInfo::typeid) {
         Console::WriteLine("   Returning an en-US date/time format provider.");
         culture = gcnew CultureInfo("en-US");
         return culture->DateTimeFormat;
      }
      else {
         Console::WriteLine("   Requesting a format provider of {0}.", formatType->Name);
         return nullptr;
      }
   }
};

void main()
{
   array<Object^>^ values = gcnew array<Object^> { 103.5, gcnew DateTime(2010, 12, 26, 14, 34, 0) };
   IFormatProvider^ provider = gcnew InterceptProvider();
      
   // Convert value to each of the types represented in TypeCode enum.
   for each (Object^ value in values)
   {
      // Iterate types in TypeCode enum.
      for each (TypeCode enumType in (array<TypeCode>^) Enum::GetValues(TypeCode::typeid))
      {         
         if (enumType == TypeCode::DBNull || enumType == TypeCode::Empty) continue;
            
         try {
            Console::WriteLine("{0} ({1}) --> {2} ({3}).", 
                              value, value->GetType()->Name,
                              Convert::ChangeType(value, enumType, provider),
                              enumType.ToString());
         }
         catch (InvalidCastException^ e) {
            Console::WriteLine("Cannot convert a {0} to a {1}",
                              value->GetType()->Name, enumType.ToString());
         }                     
         catch (OverflowException^ e) {
            Console::WriteLine("Overflow: {0} is out of the range of a {1}",
                              value, enumType.ToString());
         }
      }
      Console::WriteLine();
   }
}
// The example displays the following output:
//    103.5 (Double) --> 103.5 (Object).
//    103.5 (Double) --> True (Boolean).
//    Cannot convert a Double to a Char
//    103.5 (Double) --> 104 (SByte).
//    103.5 (Double) --> 104 (Byte).
//    103.5 (Double) --> 104 (Int16).
//    103.5 (Double) --> 104 (UInt16).
//    103.5 (Double) --> 104 (Int32).
//    103.5 (Double) --> 104 (UInt32).
//    103.5 (Double) --> 104 (Int64).
//    103.5 (Double) --> 104 (UInt64).
//    103.5 (Double) --> 103.5 (Single).
//    103.5 (Double) --> 103.5 (Double).
//    103.5 (Double) --> 103.5 (Decimal).
//    Cannot convert a Double to a DateTime
//       Returning a fr-FR numeric format provider.
//    103.5 (Double) --> 103,5 (String).
//    
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (Object).
//    Cannot convert a DateTime to a Boolean
//    Cannot convert a DateTime to a Char
//    Cannot convert a DateTime to a SByte
//    Cannot convert a DateTime to a Byte
//    Cannot convert a DateTime to a Int16
//    Cannot convert a DateTime to a UInt16
//    Cannot convert a DateTime to a Int32
//    Cannot convert a DateTime to a UInt32
//    Cannot convert a DateTime to a Int64
//    Cannot convert a DateTime to a UInt64
//    Cannot convert a DateTime to a Single
//    Cannot convert a DateTime to a Double
//    Cannot convert a DateTime to a Decimal
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (DateTime).
//       Returning an en-US date/time format provider.
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (String).
using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(NumberFormatInfo)) {
         Console.WriteLine("   Returning a fr-FR numeric format provider.");
         return new System.Globalization.CultureInfo("fr-FR").NumberFormat;
      }   
      else if (formatType == typeof(DateTimeFormatInfo)) {
         Console.WriteLine("   Returning an en-US date/time format provider.");
         return new System.Globalization.CultureInfo("en-US").DateTimeFormat;
      }
      else {
         Console.WriteLine("   Requesting a format provider of {0}.", formatType.Name);
         return null;
      }
   }
}

public class Example
{
   public static void Main()
   {
      object[] values = { 103.5d, new DateTime(2010, 12, 26, 14, 34, 0) };
      IFormatProvider provider = new InterceptProvider();
      
      // Convert value to each of the types represented in TypeCode enum.
      foreach (object value in values)
      {
         // Iterate types in TypeCode enum.
         foreach (TypeCode enumType in ((TypeCode[]) Enum.GetValues(typeof(TypeCode))))
         {         
            if (enumType == TypeCode.DBNull || enumType == TypeCode.Empty) continue;
            
            try {
               Console.WriteLine("{0} ({1}) --> {2} ({3}).", 
                                 value, value.GetType().Name,
                                 Convert.ChangeType(value, enumType, provider),
                                 enumType.ToString());
            }
            catch (InvalidCastException) {
               Console.WriteLine("Cannot convert a {0} to a {1}",
                                 value.GetType().Name, enumType.ToString());
            }                     
            catch (OverflowException) {
               Console.WriteLine("Overflow: {0} is out of the range of a {1}",
                                 value, enumType.ToString());
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    103.5 (Double) --> 103.5 (Object).
//    103.5 (Double) --> True (Boolean).
//    Cannot convert a Double to a Char
//    103.5 (Double) --> 104 (SByte).
//    103.5 (Double) --> 104 (Byte).
//    103.5 (Double) --> 104 (Int16).
//    103.5 (Double) --> 104 (UInt16).
//    103.5 (Double) --> 104 (Int32).
//    103.5 (Double) --> 104 (UInt32).
//    103.5 (Double) --> 104 (Int64).
//    103.5 (Double) --> 104 (UInt64).
//    103.5 (Double) --> 103.5 (Single).
//    103.5 (Double) --> 103.5 (Double).
//    103.5 (Double) --> 103.5 (Decimal).
//    Cannot convert a Double to a DateTime
//       Returning a fr-FR numeric format provider.
//    103.5 (Double) --> 103,5 (String).
//    
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (Object).
//    Cannot convert a DateTime to a Boolean
//    Cannot convert a DateTime to a Char
//    Cannot convert a DateTime to a SByte
//    Cannot convert a DateTime to a Byte
//    Cannot convert a DateTime to a Int16
//    Cannot convert a DateTime to a UInt16
//    Cannot convert a DateTime to a Int32
//    Cannot convert a DateTime to a UInt32
//    Cannot convert a DateTime to a Int64
//    Cannot convert a DateTime to a UInt64
//    Cannot convert a DateTime to a Single
//    Cannot convert a DateTime to a Double
//    Cannot convert a DateTime to a Decimal
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (DateTime).
//       Returning an en-US date/time format provider.
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (String).
Imports System.Globalization

Public Class InterceptProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
          Implements IFormatProvider.GetFormat
      If formatType.Equals(GetType(NumberFormatInfo)) Then
         Console.WriteLine("   Returning a fr-FR numeric format provider.")
         Return New CultureInfo("fr-FR").NumberFormat
      ElseIf formatType.Equals(GetType(DateTimeFormatInfo)) Then
         Console.WriteLine("   Returning an en-US date/time format provider.")
         Return New CultureInfo("en-US").DateTimeFormat
      Else
         Console.WriteLine("   Requesting a format provider of {0}.", formatType.Name)
         Return Nothing
      End If
   End Function
End Class

Module Example
   Public Sub Main()
      Dim values() As Object = { 103.5r, #12/26/2010 2:34PM# }
      Dim provider As New InterceptProvider()
      
      ' Convert value to each of the types represented in TypeCode enum.
      For Each value As Object In values
         ' Iterate types in TypeCode enum.
         For Each enumType As TypeCode In DirectCast([Enum].GetValues(GetType(TypeCode)), TypeCode())         
            If enumType = TypeCode.DbNull Or enumType = TypeCode.Empty Then Continue For
            
            Try
               Console.WriteLine("{0} ({1}) --> {2} ({3}).", _
                                 value, value.GetType().Name, _
                                 Convert.ChangeType(value, enumType, provider), _
                                 enumType.ToString())
            Catch e As InvalidCastException
               Console.WriteLine("Cannot convert a {0} to a {1}", _
                                 value.GetType().Name, enumType.ToString())
            Catch e As OverflowException
               Console.WriteLine("Overflow: {0} is out of the range of a {1}", _
                                 value, enumType.ToString())
            End Try
         Next
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'    103.5 (Double) --> 103.5 (Object).
'    103.5 (Double) --> True (Boolean).
'    Cannot convert a Double to a Char
'    103.5 (Double) --> 104 (SByte).
'    103.5 (Double) --> 104 (Byte).
'    103.5 (Double) --> 104 (Int16).
'    103.5 (Double) --> 104 (UInt16).
'    103.5 (Double) --> 104 (Int32).
'    103.5 (Double) --> 104 (UInt32).
'    103.5 (Double) --> 104 (Int64).
'    103.5 (Double) --> 104 (UInt64).
'    103.5 (Double) --> 103.5 (Single).
'    103.5 (Double) --> 103.5 (Double).
'    103.5 (Double) --> 103.5 (Decimal).
'    Cannot convert a Double to a DateTime
'       Returning a fr-FR numeric format provider.
'    103.5 (Double) --> 103,5 (String).
'    
'    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (Object).
'    Cannot convert a DateTime to a Boolean
'    Cannot convert a DateTime to a Char
'    Cannot convert a DateTime to a SByte
'    Cannot convert a DateTime to a Byte
'    Cannot convert a DateTime to a Int16
'    Cannot convert a DateTime to a UInt16
'    Cannot convert a DateTime to a Int32
'    Cannot convert a DateTime to a UInt32
'    Cannot convert a DateTime to a Int64
'    Cannot convert a DateTime to a UInt64
'    Cannot convert a DateTime to a Single
'    Cannot convert a DateTime to a Double
'    Cannot convert a DateTime to a Decimal
'    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (DateTime).
'       Returning an en-US date/time format provider.
'    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (String).

설명

ChangeType(Object, TypeCode, IFormatProvider) 지정한 개체를 변환 하는 범용 변환 메서드는 value 미리 정의 된 형식으로 지정 된 typeCode합니다.ChangeType(Object, TypeCode, IFormatProvider) is a general-purpose conversion method that converts the object specified by value to a predefined type specified by typeCode. value 매개 변수는 모든 형식의 개체를 수 있습니다.The value parameter can be an object of any type. 변환이 성공 하기 value 구현 해야 합니다 IConvertible 메서드는 단순히 적절 한 호출을 래핑한 때문 IConvertible 메서드.For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. 메서드는 변환 해야 valuetypeCode 지원 합니다.The method also requires that conversion of value to typeCode be supported.

합니다 ChangeType(Object, TypeCode, IFormatProvider) 메서드의 변환을 지원 하지 않습니다 value 사용자 지정 형식입니다.The ChangeType(Object, TypeCode, IFormatProvider) method does not support the conversion of value to a custom type. 이러한 변환은 수행 하려면 호출을 ChangeType(Object, Type, IFormatProvider) 메서드.To perform such a conversion, call the ChangeType(Object, Type, IFormatProvider) method.

합니다 provider 매개 변수는는 IFormatProvider 변환에 대 한 서식 지정 정보를 제공 합니다.The provider parameter is an IFormatProvider implementation that supplies formatting information for the conversion. 기본 종속이 매개 변수는 사용 여부 및 방법을 IConvertible 구현 합니다.Whether and how this parameter is used depends on the underlying IConvertible implementation. 하는 경우 value 기본 데이터 형식인 provider 다음 변환에만 사용 됩니다.If value is a base data type, provider is used only for the following conversions. 경우는 null IFormatProvider 인수를 이러한 메서드에 전달 됩니다는 CultureInfo 현재 스레드 문화권을 나타내는 개체를 사용 합니다.If a nullIFormatProvider argument is passed to these methods, the CultureInfo object that represents the current thread culture is used.

하는 경우 value 가 애플리케이션 정의 형식이 해당 IConvertible 구현을 사용할 수는 provider 매개 변수입니다.If value is an application-defined type, its IConvertible implementation may use the provider parameter.

적용 대상