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

c#字符串转int

作者:冥界少主   发布日期:2025-05-15   浏览:71

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

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("转换失败,输入的字符串不是有效的整数。");
        }
    }
}

解释说明:

  1. int.Parse:此方法尝试将字符串解析为整数。如果字符串格式不正确或超出整数范围,则会抛出异常(FormatExceptionOverflowException)。因此,通常建议在使用 int.Parse 时使用 try-catch 块来捕获可能的异常。

  2. int.TryParse:此方法是一个更安全的选择,它不会抛出异常。相反,它返回一个布尔值,指示转换是否成功,并通过 out 参数输出转换后的整数值。如果转换失败,out 参数将被设置为默认值(0)。

上一篇:c# 输出

下一篇:c# directory

大家都在看

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 中文站