TryParse 란
문자열 데이터를 다양한 데이터 형식으로 변환할 때, 예외 처리와 데이터 유효성을 다루는 문제를 처리할 때 활용될 수 있습니다.
문자열을 변환하려는 데이터 형식으로 안전하게 변환할 수 있으며, 변환이 실패하는 경우 예외를 방지할 수 있습니다.
변환이 성공하면 true를 반환하고, 변환된 값을 지정한 변수에 저장합니다.
변환이 실패하면 false를 반환하고 변수에는 해당 데이터 형식의 기본값이 유지됩니다.
예제
1. Int 변환
using UnityEngine;
public class IntegerConversionExample : MonoBehaviour
{
void Start()
{
string input = "123";
int number;
if (int.TryParse(input, out number))
{
Debug.Log("Conversion successful. Number: " + number);
}
else
{
Debug.Log("Conversion failed.");
}
}
}
결과 값 => Conversion successful. Number: 123
2. Bool 변환
using UnityEngine;
public class BooleanConversionExample : MonoBehaviour
{
void Start()
{
string input = "true";
bool value;
if (bool.TryParse(input, out value))
{
Debug.Log("Conversion successful. Value: " + value);
}
else
{
Debug.Log("Conversion failed.");
}
}
}
결과 값 => Conversion successful. Value: true