Convert Object to Int in C# Safely
In C#, when converting an object type to an int type, if the object’s value is not a valid int type, it will throw an InvalidCastException exception. To address this issue, you can use the int.TryParse method to attempt to convert the object to an int instead of using a type cast. This way, if the conversion fails, it won’t throw an exception but will return a boolean value indicating whether the conversion was successful.
Here is an example:
object obj = 10;
int result;
if (int.TryParse(obj.ToString(), out result))
{
// 转换成功
Console.WriteLine(result);
}
else
{
// 转换失败
Console.WriteLine("无法将对象转换为int");
}
In the example above, we first use the ToString method to convert the object into a string, and then use the int.TryParse method to attempt to convert the string into an integer. If the conversion is successful, the result will be stored in the result variable and can be further used. If the conversion fails, an error message will be outputted.
Using the int.TryParse method can prevent exceptions and offer better error handling.