HTML 테이블에서 데이터를 가져 오는 소프트웨어를 개발 중입니다. 그래서이 줄 :
team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim();
반환 : ""
(나는 DOM 조작을 위해 html 민첩성 팩을 사용하고 있습니다.)
그리고 완전한 라인은 이것입니다 :
Convert.ToInt32(
team.SelectSingleNode(
".//td[@class='number total won total_won']")
?.InnerText.Trim());
이것은 예외 (잘못된 형식 예외)를 반환합니다.
이 문제를 해결할 수있는 아이디어가 있습니까?
Convert.ToInt32
대신 int.TryParse
를 사용할 수 있습니다.
int myInt;
if(!int.TryParse(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim(), out myInt))
{
myInt = 0;
}
알아요,하지만 30 + 라인의 코드를했습니다. 그래서 조건을 많이 추가해야합니다 ... - Ilnumerouno 지금 막
대신 도우미 메서드를 작성할 수 있습니다.
public static class Converter{
public static int ConvertToInt(string stringAsInt){
int myInt;
return int.TryParse(stringAsInt, out myInt) ? myInt : 0;
}
}
코드 호출.
var parsedInt = Converter.ConvertToInt(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim());