// 将字符串转换为整数的示例代码
string strNumber = "123"; // 定义一个字符串,内容为数字字符
int number;
// 使用 int.Parse 方法进行转换
try
{
number = int.Parse(strNumber);
Console.WriteLine("转换成功: " + number);
}
catch (FormatException)
{
Console.WriteLine("格式错误,无法转换为整数");
}
catch (OverflowException)
{
Console.WriteLine("数值超出 int 类型范围");
}
// 使用 int.TryParse 方法进行转换,推荐使用此方法因为它不会抛出异常
if (int.TryParse(strNumber, out number))
{
Console.WriteLine("转换成功: " + number);
}
else
{
Console.WriteLine("转换失败");
}
int.Parse
方法:直接将字符串转换为整数。如果字符串格式不正确或超出 int
类型的范围,会抛出异常(FormatException
或 OverflowException
)。因此,通常需要使用 try-catch
块来捕获可能的异常。
int.TryParse
方法:这是推荐的方法,因为它不会抛出异常。它返回一个布尔值,表示转换是否成功,并通过 out
参数输出转换后的整数值。如果转换失败,out
参数会被设置为 0
。
上一篇:c# ^
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站