다음을 통해 공유


Convert 클래스

기본 데이터 형식을 다른 데이터 형식으로 변환합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public NotInheritable Class Convert
‘사용 방법
정적 클래스의 멤버는 클래스 인스턴스를 사용하지 않고 직접 액세스할 수 있습니다.
public static class Convert
public ref class Convert abstract sealed
public final class Convert
public final class Convert

설명

이 클래스는 지정된 형식과 동일한 값을 갖는 기본 형식을 반환합니다. 지원되는 기본 형식으로는 Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTimeString이 있습니다.

변환 메서드는 각 기본 형식을 각각 다른 기본 형식으로 변환합니다. 그러나 실제 변환 작업은 다음과 같은 세 가지로 크게 분류됩니다.

  • 한 형식을 자신으로 변환하면 단순히 해당 형식을 반환하게 됩니다. 실제로는 변환이 수행되지 않습니다.

  • 변환한 결과가 의미 없으면 InvalidCastException을 throw합니다. 실제로는 변환이 수행되지 않습니다. CharBoolean, Single, Double, Decimal 또는 DateTime으로 변환하거나 이러한 형식을 Char로 변환하면 예외가 throw됩니다. DateTimeString을 제외한 형식으로 변환하거나 String을 제외한 다른 형식을 DateTime으로 변환하면 예외가 throw됩니다.

  • 위에 설명한 형식을 제외한 기본 형식은 다른 기본 형식으로 변환할 수 있습니다.

숫자 형식을 변환하는 과정에서 정확성이 떨어지는 경우, 즉 최하위 유효 자릿수가 손실되는 경우 예외가 throw되지 않습니다. 그러나 반환되는 값이 특정 변환 메서드의 결과 값 형식에서 표현할 수 있는 것보다 큰 경우에는 예외가 throw됩니다.

예를 들어, DoubleSingle로 변환할 때 정밀도가 떨어질 수는 있지만 예외가 throw되지 않습니다. 그러나 Single로 표현하기에 Double의 크기가 너무 큰 경우에는 예외가 throw됩니다.

일부 메서드를 사용하면 바이트 배열과 String 또는 64자리 기수 문자로 구성된 유니코드 문자 사이를 변환할 수 있습니다. 64자리 기수로 표현되는 데이터는 7비트 문자만을 전송하는 데이터 채널을 통해 쉽게 전달될 수 있습니다.

이 클래스의 메서드 중 일부는 IFormatProvider 인터페이스를 구현하는 매개 변수 개체를 사용합니다. 이 매개 변수는 변환 프로세스를 도와주는 culture별 형식 지정 정보를 제공합니다. 이 매개 변수는 기본값 형식에서는 무시되지만 IConvertible을 구현하는 모든 사용자 정의 형식에서 사용될 수 있습니다.

기본값 형식에 대한 자세한 내용은 관련 항목을 참조하십시오.

예제

다음 코드 예제에서는 ToInt32, ToBooleanToString과 같은 Convert 클래스에 있는 일부 변환 메서드를 보여 줍니다.

Dim dNumber As Double
dNumber = 23.15

Try
   ' Returns 23
   Dim iNumber As Integer
   iNumber = System.Convert.ToInt32(dNumber)
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in double to int conversion.")
End Try

' Returns True
Dim bNumber As Boolean
bNumber = System.Convert.ToBoolean(dNumber)

' Returns "23.15"
Dim strNumber As String
strNumber = System.Convert.ToString(dNumber)

Try
   ' Returns '2'
   Dim chrNumber As Char
   chrNumber = System.Convert.ToChar(strNumber.Chars(1))
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String length is greater than 1.")
End Try

' System.Console.ReadLine() returns a string and it
' must be converted.
Dim newInteger As Integer
newInteger = 0
Try
   System.Console.WriteLine("Enter an integer:")
   newInteger = System.Convert.ToInt32(System.Console.ReadLine())
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String does not consist of an " + _
       "optional sign followed by a series of digits.")
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in string to int conversion.")
End Try

System.Console.WriteLine("Your integer as a double is {0}", _
                         System.Convert.ToDouble(newInteger))
double dNumber = 23.15;

try {
    // Returns 23
    int    iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
    System.Console.WriteLine(
                "Overflow in double to int conversion.");
}
// Returns True
bool   bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);

try {
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber[0]);
} 
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(
                        System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
    System.Console.WriteLine("String does not consist of an " +
                    "optional sign followed by a series of digits.");
} 
catch (System.OverflowException) {
    System.Console.WriteLine(
    "Overflow in string to int conversion.");
}

System.Console.WriteLine("Your integer as a double is {0}",
                         System.Convert.ToDouble(newInteger));
Double dNumber = 23.15;

try
{
   // Returns 23
   Int32 iNumber = Convert::ToInt32( dNumber );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(
      "Overflow in Double to Int32 conversion" );
}
// Returns True
Boolean bNumber = Convert::ToBoolean( dNumber );

// Returns "23.15"
String^ strNumber = Convert::ToString( dNumber );

try
{
   // Returns '2'
   Char chrNumber = Convert::ToChar( strNumber->Substring( 0, 1 ) );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String length is greater than 1" );
}

// System::Console::ReadLine() returns a string and it
// must be converted.
Int32 newInteger = 0;
try
{
   Console::WriteLine(  "Enter an integer:" );
   newInteger = Convert::ToInt32( System::Console::ReadLine() );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String does not consist of an " +
      "optional sign followed by a series of digits" );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(  "Overflow in string to Int32 conversion" );
}

Console::WriteLine( "Your integer as a Double is {0}",
   Convert::ToDouble( newInteger ) );
double dNumber = 23.15;

try {        
    // Returns 23
    int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in double to int conversion.");
}

// Returns True
boolean bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
String strNumber = System.Convert.ToString(dNumber);

try {        
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber.get_Chars(0));
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;

try {        
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(System.Console.ReadLine());
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine(("String does not consist of an " 
        + "optional sign followed by a series of digits."));
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}", 
    System.Convert.ToString(System.Convert.ToDouble(newInteger)));

다음 코드 예제에서는 Convert 클래스에 있는 일부 변환 메서드를 보여 줍니다.

' Sample for the Convert class summary.
Imports System

Class Sample
   Public Shared Sub Main()
      Dim nl As String = Environment.NewLine
      Dim str As String = "{0}Return the Int64 equivalent of the following base types:{0}"
      Dim xBool As Boolean = False
      Dim xShort As Short = 1
      Dim xInt As Integer = 2
      Dim xLong As Long = 3
      Dim xSingle As Single = 4F
      Dim xDouble As Double = 5.0
      Dim xDecimal As Decimal = 6D
      Dim xString As String = "7"
      Dim xChar As Char = "8"c ' '8' = hexadecimal 38 = decimal 56
      Dim xByte As Byte = 9
      
      '  The following types are not CLS-compliant.
      ' Dim xUshort As System.UInt16 = 120
      ' Dim xUint As System.UInt32 = 121
      ' Dim xUlong As System.UInt64 = 122
      ' Dim xSbyte As System.SByte = 123
      
      '  The following type cannot be converted to an Int64.
      '  Dim xDateTime As System.DateTime = DateTime.Now

      Console.WriteLine(str, nl)
      Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool))
      Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort))
      Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt))
      Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong))
      Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle))
      Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble))
      Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal))
      Console.WriteLine("String:   {0}", Convert.ToInt64(xString))
      Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar))
      Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte))
      Console.WriteLine("DateTime: There is no example of this conversion because")
      Console.WriteLine("          a DateTime cannot be converted to an Int64.")
      '
      Console.Write("{0}The following types are not supported: ", nl)
      Console.WriteLine("UInt16, UInt32, UInt64, and SByte")
   End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'
'Return the Int64 equivalent of the following base types:
'
'Boolean:  0
'Int16:    1
'Int32:    2
'Int64:    3
'Single:   4
'Double:   5
'Decimal:  6
'String:   7
'Char:     56
'Byte:     9
'DateTime: There is no example of this conversion because
'          a DateTime cannot be converted to an Int64.
'
'The following types are not supported: UInt16, UInt32, UInt64, and SByte
'
// Sample for the Convert class summary.
using System;

class Sample 
{
    public static void Main() 
    {
    string nl = Environment.NewLine;
    string str = "{0}Return the Int64 equivalent of the following base types:{0}";
    bool    xBool = false;
    short   xShort = 1;
    int     xInt   = 2;
    long    xLong  = 3;
    float   xSingle = 4.0f;
    double  xDouble = 5.0;
    decimal xDecimal = 6.0m;
    string  xString = "7";
    char    xChar   = '8'; // '8' = hexadecimal 38 = decimal 56
    byte    xByte  =  9;

//  The following types are not CLS-compliant.
    ushort  xUshort = 120;   
    uint    xUint =   121;
    ulong   xUlong =  122;
    sbyte   xSbyte  = 123;

//  The following type cannot be converted to an Int64.
//  DateTime xDateTime = DateTime.Now;

    Console.WriteLine(str, nl);
    Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool));
    Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort));
    Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt));
    Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong));
    Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle));
    Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble));
    Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal));
    Console.WriteLine("String:   {0}", Convert.ToInt64(xString));
    Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar));
    Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte));
    Console.WriteLine("DateTime: There is no example of this conversion because");
    Console.WriteLine("          a DateTime cannot be converted to an Int64.");
//
    Console.WriteLine("{0}The following types are not CLS-compliant.{0}", nl);
    Console.WriteLine("UInt16:   {0}", Convert.ToInt64(xUshort));
    Console.WriteLine("UInt32:   {0}", Convert.ToInt64(xUint));
    Console.WriteLine("UInt64:   {0}", Convert.ToInt64(xUlong));
    Console.WriteLine("SByte:    {0}", Convert.ToInt64(xSbyte));
    }
}
/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
          a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/
// Sample for the Convert class summary.
using namespace System;
int main()
{
   String^ nl = Environment::NewLine;
   String^ str = " {0}Return the Int64 equivalent of the following base types: {0}";
   bool xBool = false;
   short xShort = 1;
   int xInt = 2;
   long xLong = 3;
   float xSingle = 4.0f;
   double xDouble = 5.0;
   Decimal xDecimal = Decimal(6.0);
   String^ xString = "7";
   char xChar = '8'; // '8' = hexadecimal 38 = decimal 56

   Byte xByte = 9;
   
   //  The following types are not CLS-compliant.
   UInt16 xUshort = 120;
   UInt32 xUint = 121;
   UInt64 xUlong = 122;
   SByte xSbyte = 123;
   
   //  The following type cannot be converted to an Int64.
   //  DateTime xDateTime = DateTime::Now;
   Console::WriteLine( str, nl );
   Console::WriteLine( "Boolean: {0}", Convert::ToInt64( xBool ) );
   Console::WriteLine( "Int16: {0}", Convert::ToInt64( xShort ) );
   Console::WriteLine( "Int32: {0}", Convert::ToInt64( xInt ) );
   Console::WriteLine( "Int64: {0}", Convert::ToInt64( xLong ) );
   Console::WriteLine( "Single: {0}", Convert::ToInt64( xSingle ) );
   Console::WriteLine( "Double: {0}", Convert::ToInt64( xDouble ) );
   Console::WriteLine( "Decimal: {0}", Convert::ToInt64( xDecimal ) );
   Console::WriteLine( "String: {0}", Convert::ToInt64( xString ) );
   Console::WriteLine( "Char: {0}", Convert::ToInt64( xChar ) );
   Console::WriteLine( "Byte: {0}", Convert::ToInt64( xByte ) );
   Console::WriteLine( "DateTime: There is no example of this conversion because" );
   Console::WriteLine( "          a DateTime cannot be converted to an Int64." );
   
   //
   Console::WriteLine( " {0}The following types are not CLS-compliant. {0}", nl );
   Console::WriteLine( "UInt16: {0}", Convert::ToInt64( xUshort ) );
   Console::WriteLine( "UInt32: {0}", Convert::ToInt64( xUint ) );
   Console::WriteLine( "UInt64: {0}", Convert::ToInt64( xUlong ) );
   Console::WriteLine( "SByte: {0}", Convert::ToInt64( xSbyte ) );
}

/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/

상속 계층 구조

System.Object
  System.Convert

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Convert 멤버
System 네임스페이스
Object
SByte
Int16
Int32
Int64
Byte 구조체
UInt16
UInt32
UInt64
Single
Double
Decimal
Boolean 구조체
Char 구조체
String