Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 字符串转int

作者:/神經病/   发布日期:2025-04-02   浏览:120

// 将字符串转换为整数的示例代码

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("转换失败");
}

解释说明:

  1. int.Parse 方法:直接将字符串转换为整数。如果字符串格式不正确或超出 int 类型的范围,会抛出异常(FormatExceptionOverflowException)。因此,通常需要使用 try-catch 块来捕获可能的异常。

  2. int.TryParse 方法:这是推荐的方法,因为它不会抛出异常。它返回一个布尔值,表示转换是否成功,并通过 out 参数输出转换后的整数值。如果转换失败,out 参数会被设置为 0

上一篇:c# ^

下一篇:c# string 转datetime

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站