// 将字符串转换为整数的示例代码
using System;
class Program
{
static void Main()
{
string str = "123"; // 定义一个字符串,内容为"123"
// 使用 int.Parse 方法将字符串转换为整数
try
{
int number = int.Parse(str);
Console.WriteLine("转换后的整数是: " + number);
}
catch (FormatException)
{
Console.WriteLine("输入的字符串格式不正确,无法转换为整数。");
}
catch (OverflowException)
{
Console.WriteLine("输入的字符串超出整数范围,无法转换。");
}
// 使用 int.TryParse 方法将字符串转换为整数
string str2 = "456";
int number2;
bool result = int.TryParse(str2, out number2);
if (result)
{
Console.WriteLine("转换后的整数是: " + number2);
}
else
{
Console.WriteLine("转换失败,输入的字符串不是有效的整数。");
}
}
}
int.Parse:此方法尝试将字符串解析为整数。如果字符串格式不正确或超出整数范围,则会抛出异常(FormatException
或 OverflowException
)。因此,通常建议在使用 int.Parse
时使用 try-catch
块来捕获可能的异常。
int.TryParse:此方法是一个更安全的选择,它不会抛出异常。相反,它返回一个布尔值,指示转换是否成功,并通过 out
参数输出转换后的整数值。如果转换失败,out
参数将被设置为默认值(0)。
上一篇:c# 输出
下一篇:c# directory
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站