.NET 帮助

将字符串解析为整型C#(开发人员如何使用)

发布 2024年六月6日
分享:

转换数据类型 是编程中的一个基本概念,在使用 C# 编程时,最常见的任务之一就是将数字的字符串表示转换为整数。在许多应用程序中,需要将用户输入或来自外部的数据转换为数字格式,以便进行计算或其他操作,这个过程非常有用。

在本教程中,我们将探讨 C# 提供的将字符串转换为整数的不同方法。我们还将探索 IronPDF 库.

将字符串变量转换为英特变量的基础知识

Convert.ToInt32 "和 "Int32.Parse "方法是 C# 中将字符串值转换为整数值的标准工具。这些函数旨在解释输入字符串的数值并将其转换为 int。但是,如果字符串格式不正确,这些方法可能会抛出异常,因此异常处理是使用这些工具的一个重要方面。

使用 Int32.Parse 方法

Int32.Parse 方法会将有效的数字字符串直接转换为整数。该方法要求字符串是有效的数字格式,否则将抛出一个 FormatException。如果确定字符串是一个有效的数字,则可以直接使用该方法。例如

public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
Public Shared inputString As String = "123"
Public Shared result As Integer = Integer.Parse(inputString)
Console.WriteLine(result)
VB   C#

在上述代码中,inputString 包含一个有效的数字,Parse 方法会将其转换为整数 123。但是,如果 inputString 包含非数字字符或为空字符串,使用 Parse 将导致 FormatExceptionArgumentNullException 异常。

使用 Convert.ToInt32 方法

另一个将字符串转换为整数的转换类是 Convert.ToInt32。该方法与 Int32.Parse 类似,但灵活性更高。了解如何在 C# 中将字符串转换为 int,可以有效地为数据处理提供多种可能性,并确保应用程序性能稳定。它通过返回默认值 0 来处理空字符串,从而避免了抛出异常。下面介绍如何使用它:

public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
Public Shared inputString As String = Nothing
Public Shared result As Integer = Convert.ToInt32(inputString)
Console.WriteLine(result)
VB   C#

此方法会将 inputString 转换为 0,而不会抛出异常,因此对于可能未正确初始化的变量更安全。

使用 Int32.TryParse 的高级技术

为了更好地控制转换过程,特别是在处理可能不可靠的用户输入时,Int32.TryParse是一种首选方法。该方法尝试解析数字字符串,并返回一个布尔值,表示 TryParse 方法是否成功地将字符串转换为整数。它使用一个 out 参数来返回转换后的整数。

使用 Int32.TryParse 的示例

下面是如何使用 Int32.TryParse 方法将字符串输入安全地转换为整数值,并优雅地处理任何无效的字符串输入:

string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
Dim inputString As String = "abc123"
Dim num As Integer = Nothing
Dim conversionSucceeded As Boolean = Integer.TryParse(inputString, num)
If conversionSucceeded Then
	Console.WriteLine("Successfully parsed: " & num)
Else
	Console.WriteLine("Conversion failed. Provided string is not a valid integer.")
End If
VB   C#

在本例中,Int32.TryParse 返回 false,因为 inputString 不是有效的整数。输出参数 num 仍为 0,程序会通知用户转换失败,但不会抛出任何异常。

IronPDF 库简介

IronPDF 是一个强大的 C# 库,旨在为使用 .NET 框架的开发人员简化 PDF 操作。它允许创建、编辑和管理 PDF 文件。 从 HTML 直接生成 PDF 文档此外,IronPDF 还支持 CSS、JavaScript 和图像。IronPDF 的主要功能是将 HTML 内容直接转换为 PDF。

这包括转换整个网页或 HTML 字符串,使其具有高度灵活性。IronPDF 功能强大,易于集成,支持多种开发环境。

代码示例

下面是一个简单的示例,它将用于生成 PDF 的 IronPDF 与解析字符串为整数并将其显示在 PDF 中的 C# 代码相结合。本示例假定您要获取一个数字字符串,将其转换为整数,然后使用 IronPDF 在 PDF 文档中打印该整数。

using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "Your-License-Key"
		' Create a new PDF document
		Dim pdf = New ChromePdfRenderer()
		' Sample string that represents an integer
		Dim numberString As String = "12345"
		' Parse the string into an integer
		Dim number As Integer = Nothing
		Dim result As Boolean = Int32.TryParse(numberString, number)
		If result Then
			' Create HTML content including the parsed number
			Dim htmlContent As String = $"<h1>The number is: {number}</h1>"
			' Generate a PDF from the HTML string
			Dim document = pdf.RenderHtmlAsPdf(htmlContent)
			' Save the PDF to a file
			document.SaveAs("Output.pdf")
			Console.WriteLine("PDF generated successfully with the number included.")
		Else
			Console.WriteLine("The string could not be parsed into an integer.")
		End If
	End Sub
End Class
VB   C#

将字符串解析为 Int C#(如何为开发人员工作):图 1 - 上一代码示例的 PDF 输出结果

结论

将字符串转换为整数是 C# 编程中的常见要求,尤其是在处理来自用户或外部来源的数据输入时。了解 Int32.ParseConvert.ToInt32TryParse方法之间的区别对于编写健壮且抗错的代码至关重要。

通过有效使用这些方法,您可以确保您的应用程序能够处理各种输入格式,并对无效数据做出优雅的响应。 IronPDF 用户在购买之前可以探索其功能。对于那些希望将 IronPDF 长期集成到其项目中的用户,IronPDF 可提供以下功能 授权 从 $749 开始。

< 前一页
Rebus .NET Core 示例(对开发人员的工作原理)
下一步 >
C# 调用基类构造函数(开发人员如何实现)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >