跳過到頁腳內容
.NET幫助

Parse String to Int C#(對於開發者的運行原理)

轉換資料類型是程式設計中的基本概念,在 C# 程式設計中,將數字的字串表示轉換為整數是最常見的任務之一。 此過程在許多應用中非常有用,可以將用戶輸入或外部來源的資料轉換為數字格式以進行計算或其他操作。

在本教程中,我們將探索 C# 提供的不同方法來將字串轉換成整數。 我們還將探索 IronPDF 的圖書館首頁

將字串變數轉換為 Int 的基礎

Convert.ToInt32Int32.Parse 方法是 C# 中將字串值轉換成整數值的標準工具。 這些函數旨在解釋輸入字符串的數值並將其轉換為整數。 然而,這些方法可能會拋出例外情況,如果字符串格式不正確,這使得處理例外成為使用這些工具的重要方面。

使用 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)
$vbLabelText   $csharpLabel

在上述程式碼中,inputString 包含了一個有效數字,並且 Parse 方法將其轉換為整數 123。但是,如果inputString包含非數字字符或者是一個空字符串,使用 Parse 會導致 FormatExceptionArgumentNullException

使用 Convert.ToInt32 方法

另一種將字符串轉換為整數的方法是 Convert.ToInt32。 這種方法類似於 Int32.Parse,但提供了更多的靈活性。 它能通過返回默認值為零來處理空和空字符串,這避免了拋出異常。 您可以按照以下方式使用它:

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)
$vbLabelText   $csharpLabel

使用此方法,將 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
$vbLabelText   $csharpLabel

在此示例中,Int32.TryParse 返回 false,因為 inputString 並不是一個有效的整數。 out 參數 num 保持為 0,並且程序在沒有拋出任何異常的情況下通知用戶轉換失敗。

IronPDF 函式庫介紹

IronPDF 概述部分 是一個強大的 C# 庫,旨在簡化使用 .NET 框架的開發人員的 PDF 操作。 它允許創建、編輯和管理 直接從 HTML、CSS、JavaScript 和圖像生成的 PDF 文檔。 IronPDF 的主要功能是能夠直接將 HTML 內容轉換為 PDF。

這包括轉換整個網頁或 HTML 字串,使其具有很高的靈活性。 IronPDF 被設計為既強大又易於集成,支持多種開發環境。

代碼示例

這裡有一個簡單的示例,將 IronPDF 用於 PDF 生成與 C# 代碼結合起來解析一個字符串並在 PDF 中顯示它。 此示例假定您要將一個數字字串轉換為整數,然後使用 IronPDF 在 PDF 文檔中打印該整數。

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // License your IronPdf installation
        License.LicenseKey = "Your-License-Key";

        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Sample string that represents an integer
        string numberString = "12345";

        // Attempt to 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 your IronPdf installation
        License.LicenseKey = "Your-License-Key";

        // Create a new PDF document
        var pdf = new ChromePdfRenderer();

        // Sample string that represents an integer
        string numberString = "12345";

        // Attempt to 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 your IronPdf installation
		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"

		' Attempt to 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
$vbLabelText   $csharpLabel

解析字符串到整數 C#(開發人員如何操作):圖 1 - 輸出的 PDF 來自前面的代碼示例

結論

將字符串轉換為整數是 C# 程式設計中的常見要求,尤其是當涉及到來自用戶或外部來源的資料輸入時。 理解 Int32.ParseConvert.ToInt32TryParse 方法之間的差異對於編寫健壯和錯誤抵抗的代碼至關重要。

通過有效地使用這些方法,您可以確保您的應用程序能夠處理各種輸入格式,並對無效資料作出優雅的回應。 探索 IronPDF 的免費試用許可證 以便在購買之前探索其功能。 對於那些希望長期將 IronPDF 集成到其項目中的人,IronPDF 許可選項 從 $799 開始。

常見問題解答

我如何在 C# 中將字串轉換為整數?

在 C# 中,你可以使用 Convert.ToInt32Int32.ParseInt32.TryParse 等方法来将字符串转换为整数。每种方法都有其自身的优势,其中 Int32.TryParse 是处理无效输入而不产生异常的理想选择。

在 C# 中,将用户输入的字符串转换为整数的最佳方法是什么?

Int32.TryParse 方法被推荐用于在 C# 中将用户输入字符串转换为整数,因为它提供了一个布尔结果,指示成功或失败,从而允许程序在不抛出异常的情况下优雅地处理无效输入。

Convert.ToInt32 方法在 C# 中如何处理空或空字符串?

C# 中的 Convert.ToInt32 方法通过返回默认整数值0来处理空或空字符串,从而避免了因无效输入可能引发的异常。

在 C# 中使用 Int32.Parse 时为什么需要异常处理?

使用 Int32.Parse 时需要异常处理,因为如果输入字符串不是有效的数字格式或为空,它会抛出 FormatException,如果没有正确管理,会中断程序流程。

IronPDF 能否用于将解析的整数集成到 PDF 文档中?

是的,IronPDF 可以用于将包括解析整数在内的 HTML 内容直接转换为 PDF 文档,从而促进格式化数字数据的显示和分发。

在 C# 中,将字符串转换为整数的实际应用是什么?

一个实际应用是将用户输入或外部数据转换为数字格式,用于应用程序中的计算或处理,例如在财务计算或统计分析中。

IronPDF 如何在 C# 应用程序中协助 PDF 创建?

IronPDF 是一个 C# 库,通过允许开发人员从 HTML、CSS、JavaScript 和图像生成、编辑和管理 PDF,协助 PDF 创建,是将 Web 内容集成到 PDF 文档中的理想工具。

在 C# 中使用 Int32.TryParse 进行整数转换有哪些好处?

Int32.TryParse 的好处在于它不会为无效输入抛出异常。它提供一个布尔值,指示转换的成功,从而允许开发人员以受控的方式处理错误。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。