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

c# string 转 int

作者:堕魂灭天   发布日期:2025-12-20   浏览:96

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

string strNumber = "123";

// 方法 1: 使用 int.Parse()
try
{
    int number1 = int.Parse(strNumber);
    Console.WriteLine("转换成功: " + number1);
}
catch (FormatException)
{
    Console.WriteLine("格式错误,无法转换为整数");
}
catch (OverflowException)
{
    Console.WriteLine("数值超出范围,无法转换为整数");
}

// 方法 2: 使用 int.TryParse()
int number2;
bool result = int.TryParse(strNumber, out number2);

if (result)
{
    Console.WriteLine("转换成功: " + number2);
}
else
{
    Console.WriteLine("转换失败");
}

解释说明:

  1. int.Parse():

    • 这是一个简单直接的方法,可以将字符串转换为整数。
    • 如果字符串格式不正确或数值超出整数范围,会抛出 FormatExceptionOverflowException 异常。
  2. int.TryParse():

    • 这是一个更安全的方法,不会抛出异常。
    • 它返回一个布尔值,表示转换是否成功,并通过 out 参数输出转换后的整数值。
    • 推荐在不确定输入的情况下使用此方法,以避免程序崩溃。

上一篇:c# 读取csv

下一篇:c# 列表

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

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

Laravel 中文站