C#에서 int.Parse 또는 Convert.ToInt32 메서드를 사용하여 숫자의 문자열 표현을 정수로 변환합니다. 문자열을 변환할 수 없으면 int.Parse 또는 Convert.ToInt32 메서드가 예외를 반환합니다.
Convert.ToInt32는 null 값을 허용하고 오류를 발생시키지 않습니다. Int.parse는 null 값을 허용하지 않으며 ArgumentNullException 오류를 발생시킵니다.
예
class Program {
static void Main() {
int res;
string myStr = "5000";
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} 출력
Converting String is a numeric representation: 5000
예
class Program {
static void Main() {
int res;
string myStr = null;
res = Convert.ToInt32(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} 출력
Converting String is a numeric representation: 0
예
class Program {
static void Main() {
int res;
string myStr = null;
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
} 출력
Unhandled exception. System.ArgumentNullException: Value cannot be null.