어떻게 변환하지 못한 값을 얻을 수 있습니까? 일반적으로이 단일 사례의 경우는 아닙니다.예외를 발생시키는 값
try
{
textBox1.Text = "abc";
int id = Convert.ToInt(textBox1.Text);
}
catch
{
// Somehow get the value for the parameter to the .ToInt method here
}
어떻게 변환하지 못한 값을 얻을 수 있습니까? 일반적으로이 단일 사례의 경우는 아닙니다.예외를 발생시키는 값
try
{
textBox1.Text = "abc";
int id = Convert.ToInt(textBox1.Text);
}
catch
{
// Somehow get the value for the parameter to the .ToInt method here
}
이렇게 할 수 있습니까?
int id;
if(int.TryParse(textbox.Text, out id)
{
//Do something
}
else
{
MessageBox.Show(textbox.Text);
}
예외 제안을 catch하고 catch에 textbox.Text를 표시하려면 try catch를 초기 제안으로 사용할 수도 있습니다.
편집 : (질문 변경 후) 변환 할 수없는 값을 표시하려면 다음과 같이하십시오.
string myValue = "some text";
int id = 0;
try
{
id = Convert.ToInt32(myValue);
}
catch (FormatException e)
{
MessageBox.Show(String.Format("Unable to convert {0} to int", myValue));
}
좀 더 도움이 ?? –
@NomanNasir 무슨 뜻입니까? –
@NomanNasir, 나는 당신이 생각한 것에 따라 내 대답을 업데이트했습니다 ... (어둠 속에서 넘어지기) –
더 비싼 예외를 잡는 대신 int.TryParse()를 사용하십시오. TryParse는 변환이 실패했는지 성공했는지 여부를 지정하는 부울을 반환합니다. 또한 변환 된 값을 출력 매개 변수로 반환합니다.
int result = 0;
string input = "abc";
if (int.TryParse(input, out result))
{
//Converted value is in out parameter
}
else
{
//Handle invalid input here
}
예, 예외는 (상대적으로) 비싸지 만 예외가 실제로 생성되는 경우에만 비용을 부담합니다 던져. –
예, 그것이 제가 의미했던 것입니다. 그렇기 때문에 논리에 예외를 사용하는 것은 나쁜 습관입니다. – rro
나는 convert.in catch 섹션에 실패한 값을 가져와야합니다. –
이 정보가 필요하십니까? * 원인 예외
int i = 0;
if (Int32.TryParse (textbox.Text, out i))
{
// i is good here
}
else
{
// i is BAD here, do something about it, like displaying a validation message
}
textBox1.Text = "abc";
try
{
int id = Convert.ToInt(textBox1.Text);
}
catch(FormatException ex)
{
MessageBox.Show(textBox1.Text);
}
값 *? –
나는 그가 던지기 시도를 의미한다고 생각한다. –
그는 그가 의미하는 것 같아. 그 질문에 문제가있다 ... –