2017-01-29 1 views
0

제 코드 개선에 도움을주십시오. 아이디어는 다음과 같습니다 문자열이 괜찮 경우 다음 그냥 null 또는 빈 문자열을 확인 않습니다문자열을 확인하고 C로 int로 변환하는 가장 좋은 방법 #

1을 int로 변환

int t=0; 
if(!string.IsNullOrEmpty(textbox1.text.trim()) 
    t= int.Parse(textbox1.text.trim()); 

2

if(int.tryparse(textbox1.text.trim(), out t)  
    t=int.Parse(textbox1.text.trim()); 

또는 shortif

return string.IsNullOrEmpty(textbox1.text.trim()) ? 0 : int.Parse(textbox1.text.trim()); 

더 좋은 방법이 있습니까?

+1

"확인"당신의 정의는 무엇입니까 0 인 경우? –

+1

'textbox1.text'가'null'이라면'textbox1.text.trim()'에'NullReferenceException'이 생깁니다. '! string.IsNullOrEmpty' 체크는 도움이되지 않습니다. – Guy

+1

Textbox1.Text는 null이 아닙니다 – Steve

답변

3

사용자의 입력을 얻고 정수로 변환하는 올바른 방법은 Int32.TryParse 방법을 통해서이다. 이 방법은 입력 (구문 분석 또는 Convert.ToInt32처럼) 잘못되면 비용이 많이 드는 예외를 던지지 할 수있는 장점이 있지만, 참 또는 거짓이 당신의 사용자에게 의미있는 오류 메시지를 표시 할 수 있도록 반환합니다.

textbox1.Text는 null이 아니므로 명시 적으로 확인할 필요가 없습니다. 나는이 textbox1이 InitializeComponent 호출에 정의 된 TextBox 컨트롤이므로 null이 아니라고 가정합니다.

+0

몸이없는 IF 블록처럼 보입니까? – jaleel

+0

그것은 단지 예일뿐입니다. 주석 대신 t 변수 또는 메시지를 사용하는 코드를 사용자에게 추가하십시오. – Steve

+0

도와주세요 : – jaleel

1
int t = 0; 
int.TryParse(textbox1?.Text?.Trim(), out t); 
0
int i = 0; 

Int32.TryParse(TextBox1.Text, out i); 
0

예. TryParse가 true 또는 not를 반환하는지 확인해야합니다. true의 경우 그것은 성공 &에 대한 occurs.The TryParse 오류가 0을 반환합니다 경우는 false 모두 ​​TryParse이 실패 또는 실제 문자열 값이

string s2 = "13.3"; 
int i; 

//i = Convert.ToInt32(s2);     // Run Time Error 
Console.WriteLine(int.TryParse(s2, out i)); // False 
Console.WriteLine(i);      // Output will be 0 

string s3 = "Hello"; 
//i = Convert.ToInt32(s2);     // Run Time Error 
Console.WriteLine(int.TryParse(s3, out i)); // False 
Console.WriteLine(i);      // Output will be 0 

string s1 = null; 
Console.WriteLine(int.TryParse(s1, out i)); // False 
Console.WriteLine(i);      // Output will be 0 

string s4 = "0";  
Console.WriteLine(int.TryParse(s4, out i)); // return True 
Console.WriteLine(i);      // Output will be 0 
관련 문제