별출처 : MSDN(http://msdn.microsoft.com/ko-kr/library/bb397679.aspx)

 

 

<?XML:NAMESPACE PREFIX = [default] http://www.w3.org/1999/xhtml NS = "http://www.w3.org/1999/xhtml" />이러한 변환은 예를 들어 명령줄 인수에서 숫자 입력을 가져올 때 유용할 수 있습니다. 비슷한 메서드로 문자열을 float 또는 long 등의 다른 숫자 형식으로 변환할 수도 있습니다. 다음 표에서는 이러한 메서드를 보여 줍니다.

숫자 형식

방법

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

int

ToInt32(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

예제

 


이 예제에서는 ToInt32(String) 메서드를 호출하여 입력 stringint로 변환합니다. 프로그램이이 메서드에 의해 throw 될 수 있는 두 개의 가장 일반적인 예외를 catch 합니다. FormatExceptionOverflowException. 정수 저장소 위치를 오버플로하지 않고 숫자를 증가시킬 수 있는 경우 프로그램에서 결과에 1을 더하여 출력을 인쇄합니다.

C#

static void Main(string[] args)
{
    int numVal = -1;
    bool repeat = true;

    while (repeat == true)
    {
        Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");

        string input = Console.ReadLine();

        // ToInt32 can throw FormatException or OverflowException.
        try
        {
            numVal = Convert.ToInt32(input);
        }
        catch (FormatException e)
        {
            Console.WriteLine("Input string is not a sequence of digits.");
        }
        catch (OverflowException e)
        {
            Console.WriteLine("The number cannot fit in an Int32.");
        }
        finally
        {
            if (numVal < Int32.MaxValue)
            {
                Console.WriteLine("The new value is {0}", numVal + 1);
            }
            else
            {
                Console.WriteLine("numVal cannot be incremented beyond its current value");
            }
        }
        Console.WriteLine("Go again? Y/N");
        string go = Console.ReadLine();
        if (go == "Y" || go == "y")
        {
            repeat = true;
        }
        else
        {
            repeat = false;
        }
    }
    // Keep the console open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();    
}
// Sample Output:
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 473
// The new value is 474
// Go again? Y/N
// y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 2147483647
// numVal cannot be incremented beyond its current value
// Go again? Y/N
// Y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// -1000
// The new value is -999
// Go again? Y/N
// n
// Press any key to exit.

string 을 int로 변환하는 또 다른 방법은 System.Int32 구조체의 Parse 또는 TryParse 메서드를 사용하는 것입니다. ToUInt32 메서드는 Parse를 내부적으로 사용합니다. 문자열이 올바른 형식이 아닌 경우 Parse는 예외를 throw하는 반면, TryParse는 예외를 throw하지 않고false를 반환합니다. 다음 예제에서는 ParseTryParse에 대한 호출이 성공하는 경우와 실패하는 경우를 모두 보여 줍니다.

C#

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105

C#

// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105

C#

try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.

C#

string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int.

+ Recent posts