// 将字符串转换为整数的示例代码
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
类型的范围,会抛出异常(如 FormatException
或 OverflowException
)。out
参数输出转换后的结果。推荐使用此方法,因为它更安全且性能更好。上一篇:c# app.config
下一篇:c#时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站