跳過到頁腳內容
.NET幫助

C# 參考傳遞 (對開發者如何運作)

有效的記憶體管理和資料處理是程式設計領域中建立高效能程式碼的必要元件。 撰寫有效且無錯誤的程式碼,需要瞭解資料如何在 C# 等語言的方法和函式之間 傳輸。 對於這個程序而言,有一個想法至關重要,那就是 "pass by reference"。我們將在本篇文章中探討 C# 中的參照傳遞 (pass-by-reference) 的意義,以及適當的使用情境。

如何使用 C# Pass by Reference

1.使用 Ref 參數定義一個方法。 2.初始化變數。 3.使用 Ref 關鍵字呼叫方法。 4.修改方法內部的變數。 5.觀察主要方法的變更。 6.定義帶 Out 參數的另一個方法來產生 PDF。 7.初始化並呼叫 Out 方法。

What is Pass by Reference in C#?

利用參照傳送是指 C# 中透過提供被呼叫方法的初始變數的參照,而非其值的複本,來傳送參數給函數或方法的方式。 這意味著在方法內部對參數所做的任何變更,也會對方法外部的初始變數造成影響。

C# 中的值型變數(如 int、float、bool 等)通常由 value 提供,這表示方法會收到變數值的副本。 不過,你可以使用 ref 關鍵字告訴編譯器按引用傳遞參數。

使用 ref 關鍵字

在 C# 中,可以使用 ref 關鍵字為透過引用傳遞的參考參數設定參數。 對使用 ref 關鍵字透過引用提供的參數進行的任何修改都會對原始變數產生影響。

class Program
{
    static void Main(string[] args)
    {
        int num = 10;
        Console.WriteLine("Before: " + num); // Output: Before: 10
        ModifyByRef(ref num);
        Console.WriteLine("After: " + num);  // Output: After: 20
    }

    // Method that modifies the integer by reference
    static void ModifyByRef(ref int x)
    {
        x = x * 2; // Modify the original value by reference
    }
}
class Program
{
    static void Main(string[] args)
    {
        int num = 10;
        Console.WriteLine("Before: " + num); // Output: Before: 10
        ModifyByRef(ref num);
        Console.WriteLine("After: " + num);  // Output: After: 20
    }

    // Method that modifies the integer by reference
    static void ModifyByRef(ref int x)
    {
        x = x * 2; // Modify the original value by reference
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim num As Integer = 10
		Console.WriteLine("Before: " & num) ' Output: Before: 10
		ModifyByRef(num)
		Console.WriteLine("After: " & num) ' Output: After: 20
	End Sub

	' Method that modifies the integer by reference
	Private Shared Sub ModifyByRef(ByRef x As Integer)
		x = x * 2 ' Modify the original value by reference
	End Sub
End Class
$vbLabelText   $csharpLabel

上面的範例中的 ModifyByRef 方法使用 ref 關鍵字按引用接受整數參數 x。 在方法內部對 ref 參數 x 所做的任何修改,都會立即對方法外部的 num 變數產生影響,當使用 ref num 呼叫該方法時。

out 關鍵字

out 關鍵字用於透過引用呼叫方法傳遞參數,就像 ref 一樣。 因此,方法能夠回傳許多值。

class Program
{
    static void Main(string[] args)
    {
        int result;
        Calculate(10, 5, out result);
        Console.WriteLine("Result: " + result); // Output: Result: 15
    }

    // Method that calculates the sum of two integers and outputs the result by reference
    static void Calculate(int x, int y, out int result)
    {
        result = x + y; // Assign the sum to the out parameter
    }
}
class Program
{
    static void Main(string[] args)
    {
        int result;
        Calculate(10, 5, out result);
        Console.WriteLine("Result: " + result); // Output: Result: 15
    }

    // Method that calculates the sum of two integers and outputs the result by reference
    static void Calculate(int x, int y, out int result)
    {
        result = x + y; // Assign the sum to the out parameter
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim result As Integer = Nothing
		Calculate(10, 5, result)
		Console.WriteLine("Result: " & result) ' Output: Result: 15
	End Sub

	' Method that calculates the sum of two integers and outputs the result by reference
	Private Shared Sub Calculate(ByVal x As Integer, ByVal y As Integer, ByRef result As Integer)
		result = x + y ' Assign the sum to the out parameter
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個例子中,兩個整數參數 xy,以及一個額外的參數 result(用 out 關鍵字標記)被傳遞給 Calculate 方法。 在計算 xy 的總和之後,結果被賦值給 result 參數。 result 不需要在傳送到方法之前進行初始化,因為它被標記為 out

何時使用引用傳遞

要寫出有效率且可維護的程式碼,就必須知道何時該使用旁徵博引 (pass-by-reference)。 以下情況需要使用逐字參考:

修改多個變數

當一個方法需要變更數個變數,而這些變更需要反映在方法之外時,以參照方式傳遞參數可能會有所幫助。 變數可以透過參照傳送,並直接在方法中變更,而不是讓程序傳回多個值。

// Method that modifies multiple variables by reference
static void ModifyMultipleByRef(ref int a, ref int b)
{
    a *= 2; // Double the first variable
    b *= 3; // Triple the second variable
}
// Method that modifies multiple variables by reference
static void ModifyMultipleByRef(ref int a, ref int b)
{
    a *= 2; // Double the first variable
    b *= 3; // Triple the second variable
}
' Method that modifies multiple variables by reference
Shared Sub ModifyMultipleByRef(ByRef a As Integer, ByRef b As Integer)
	a *= 2 ' Double the first variable
	b *= 3 ' Triple the second variable
End Sub
$vbLabelText   $csharpLabel

大型資料結構

透過參考方式傳遞大型資料結構 (例如陣列或複雜物件),可避免不必要的資料重複,進而提升效率。 不過,在處理大型資料結構時,應謹慎使用 Pass-by-reference,因為如果處理不當,可能會產生意想不到的後果。

與外部程式碼的互通性

在與外部程式庫互動或整合本機程式碼時,可能需要以參照方式傳送參數,以便同時遵守方法定義和外部程式碼的要求。

什麼是 IronPDF?

IronPDF 可讓程式設計師在 .NET 應用程式中建立、修改及渲染 PDF 文件。 其豐富的功能集使處理 PDF 檔案變得簡單。 您可以從 HTML、照片和其他格式建立 PDF 文件; 用文字、圖片和其他資料註解 PDF; 以及分割、合併和編輯預先存在的 PDF 文件。

IronPDF 的主要功能是能夠將 HTML 轉換為 PDF,確保版面設計和樣式得以保留。 此功能非常適合從網頁內容(如報告、發票和文件)產生 PDF。 它可將 HTML 檔案、URL 和 HTML 字串轉換成 PDF 檔案。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF 的特點

文字與圖片註解

IronPDF 可讓您以程式化的方式在 PDF 文件中加入文字、圖片和註解。 透過此功能,您可以在 PDF 檔案上加上簽名、圖章和備註。

PDF安全性

IronPDF 允許您指定不同的權限,包括列印、複製內容和編輯文件,並且可以使用密碼加密 PDF 文件。 這有助於您控制對 PDF 檔案的存取,並保護敏感資料。

填寫互動式 PDF 表單

IronPDF 可讓您以程式化的方式填寫互動式 PDF 表單。 此功能對於使用使用者輸入或自動化表單提交來建立自訂的文件很有幫助。

PDF 壓縮與最佳化

為了在不犧牲品質的前提下盡量減少檔案大小,IronPDF 提供 PDF 檔案壓縮與最佳化的解決方案。 這降低了 PDF 文件所需的儲存空間,同時也提升了效能。

跨平台相容性

IronPDF 可在 Windows、Linux 和 macOS 等平台的 .NET 應用程式中完美運作。 ASP.NET、.NET Core 和 Xamarin 等熱門 .NET Framework 均與之整合。

建立新的 Visual Studio 專案

使用 Visual Studio 很容易建立控制台專案。 若要建立控制台應用程式,請在 Visual Studio 中執行下列動作:

在開始Visual Studio Development之前,請確定您已在電腦上安裝。

開始新專案

選擇"檔案",然後選擇"新增",最後選擇"專案"。

C# Pass by Reference (How It Works For Developers):圖 1

在"建立新專案"方塊的左側,選擇您偏好的程式語言 (例如 C#)。

Console App"或"Console App (.NET Core)"範本可從下列專案範本清單中選擇。

在"名稱"欄位中提供專案名稱。

C# Pass by Reference (How It Works For Developers):圖 2

選擇您要儲存專案的儲存位置。

按下"建立"以啟動 Console 應用程式專案。

C# Pass by Reference (How It Works For Developers):圖 3

安裝 IronPDF。

在 Visual Studio Tools 的 Tools 下,您可以找到 Visual Command-Line 介面。 選擇 NuGet 的套件管理員。 在套件管理終端標籤上,您必須鍵入下列指令。

Install-Package IronPdf

另一個選擇是使用套件管理員。 使用 NuGet Package Manager 選項可將套件直接安裝到解決方案中。 使用 NuGet 網站上的搜尋方塊來尋找套件。 以下範例截圖說明在套件管理員中尋找"IronPDF"有多容易:

C# Pass by Reference (How It Works For Developers):圖 4 - 從 NuGet 套件管理員安裝 IronPDF

相關搜尋結果清單可見上圖。 若要在您的電腦上安裝軟體,請調整這些設定。

下載並安裝套件後,即可在目前的專案中使用。

使用 IronPDF 的參考傳遞。

這是如何使用 IronPDF 的 pass-by-reference 功能的說明。

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create a PDF document
        var pdf = new IronPdf.HtmlToPdf();
        // HTML content to be converted to PDF
        string htmlContent = "<h1>Hello, IronPDF!</h1>";
        // Create a byte array to store the PDF content
        byte[] pdfBytes;
        // Convert HTML to PDF and pass the byte array by reference
        ConvertHtmlToPdf(pdf, htmlContent, out pdfBytes);
        // Save or process the PDF content
        // For demonstration, let's print the length of the PDF content
        Console.WriteLine("Length of PDF: " + pdfBytes.Length);
    }

    // Method that converts HTML content to PDF and stores it in a byte array by reference
    static void ConvertHtmlToPdf(IronPdf.HtmlToPdf pdfConverter, string htmlContent, out byte[] pdfBytes)
    {
        // Convert HTML to PDF and store the result in the byte array
        var pdfDoc = pdfConverter.RenderHtmlAsPdf(htmlContent);
        pdfBytes = pdfDoc.BinaryData;
    }
}
using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create a PDF document
        var pdf = new IronPdf.HtmlToPdf();
        // HTML content to be converted to PDF
        string htmlContent = "<h1>Hello, IronPDF!</h1>";
        // Create a byte array to store the PDF content
        byte[] pdfBytes;
        // Convert HTML to PDF and pass the byte array by reference
        ConvertHtmlToPdf(pdf, htmlContent, out pdfBytes);
        // Save or process the PDF content
        // For demonstration, let's print the length of the PDF content
        Console.WriteLine("Length of PDF: " + pdfBytes.Length);
    }

    // Method that converts HTML content to PDF and stores it in a byte array by reference
    static void ConvertHtmlToPdf(IronPdf.HtmlToPdf pdfConverter, string htmlContent, out byte[] pdfBytes)
    {
        // Convert HTML to PDF and store the result in the byte array
        var pdfDoc = pdfConverter.RenderHtmlAsPdf(htmlContent);
        pdfBytes = pdfDoc.BinaryData;
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a PDF document
		Dim pdf = New IronPdf.HtmlToPdf()
		' HTML content to be converted to PDF
		Dim htmlContent As String = "<h1>Hello, IronPDF!</h1>"
		' Create a byte array to store the PDF content
		Dim pdfBytes() As Byte = Nothing
		' Convert HTML to PDF and pass the byte array by reference
		ConvertHtmlToPdf(pdf, htmlContent, pdfBytes)
		' Save or process the PDF content
		' For demonstration, let's print the length of the PDF content
		Console.WriteLine("Length of PDF: " & pdfBytes.Length)
	End Sub

	' Method that converts HTML content to PDF and stores it in a byte array by reference
	Private Shared Sub ConvertHtmlToPdf(ByVal pdfConverter As IronPdf.HtmlToPdf, ByVal htmlContent As String, ByRef pdfBytes() As Byte)
		' Convert HTML to PDF and store the result in the byte array
		Dim pdfDoc = pdfConverter.RenderHtmlAsPdf(htmlContent)
		pdfBytes = pdfDoc.BinaryData
	End Sub
End Class
$vbLabelText   $csharpLabel

本範例中的 ConvertHtmlToPdf 函數接受三個參數:HTML 內容、名為 pdfBytes 的位元組陣列和 IronPDF HtmlToPdf 物件。 out 關鍵字表示 pdfBytes 參數是透過引用提供的,並且將在方法內部進行更改。

C# Pass by Reference (How It Works For Developers):圖 5

HTML 內容在 ConvertHtmlToPdf 函數中使用 IronPDF 渲染為 PDF 文檔,產生的二進位資料儲存在 pdfBytes 陣列中。

我們在主函數中再次使用IronPDF HTML 到 PDF 轉換,透過引用傳遞 pdfBytes 陣列。 方法呼叫之後,IronPDF 的 PDF 內容儲存在 pdfBytes 陣列的記憶體位置。

C# Pass by Reference (How It Works For Developers):圖 6

向您展示如何使用 IronPDF 和 C# 中的 pass-by-reference 高效地創建和處理 PDF 文檔。

結論

總而言之,在 C# 中使用 IronPDF 與 pass-by-reference 可以大幅提升在 .NET 程式中建立與修改 PDF 文件的能力。 有效使用 refout 關鍵字,使開發人員能夠輕鬆地透過引用傳遞參數,從而可以快速有效地修改方法中的變數和內容。 IronPDF 的功能非常廣泛,其中包括將 HTML 轉換為 PDF、根據圖像生成 PDF 以及執行廣泛的 PDF 修改任務,這些功能使開發人員能夠輕易地構建動態且互動的 PDF 文件。

IronPDF 提供加快文件處理流程所需的工具和 API,包括分割、合併、註解和優化 PDF 檔案。 此外,IronPDF 的跨平台互操作性可確保 C# 應用程式能在各種設定中輕鬆整合 PDF 功能。 基本上,開發人員可以透過融合 C# 的 pass-by-reference 優勢與 IronPDF 的豐富功能集,在應用程式中建立、修改和顯示 PDF 文件的新途徑。

最後,您可以有效率地使用 Excel、製作 PDF、執行 OCR 和使用 BarCode。 每個庫的定價從 $999 起。 如果有針對專案需求的明確授權選項,開發人員就可以放心選擇最佳模式。 憑藉這些優勢,開發人員可以有效率且透明地克服各種挑戰。

常見問題解答

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法将 HTML 字符串轉换為 PDF。此方法允許您轻松将網頁或 HTML 內容轉换為高质量的 PDF 文檔,保持原始布局和格式。

什么是 C# 中的引用傳递(pass by reference)?

C# 中的引用傳递指的是通過提供對原始变量的引用而非其值的副本来向函數或方法傳递参數。这使得在方法內部對参數的任何更改会影响原始变量。

如何在 C# 中使用 'ref' 和 'out' 关键字?

在 C# 中,'ref' 关键字用于以引用方式傳递参數,允許在方法內進行修改從而影响原始变量。'out' 关键字类似,但不需要事先初始化变量,支持方法返回多個值。

什么時候應該在 C# 中使用引用傳递?

当您需要修改多個变量、處理大型數据結构以避免不必要的复制,或与需要引用参數的外部庫交互時,應該使用引用傳递。

PDF 處理庫如何利用引用傳递?

像 IronPDF 这样的 PDF 處理庫可以利用引用傳递,通過 'out' 关键字在字节數组中存储 PDF 數据。这允許在方法中有效地處理和修改 PDF 內容,例如将 HTML 轉换為 PDF 并将結果存储在字节數组中。

使用 .NET 中的 PDF 處理庫有哪些优势?

像 IronPDF 这样的 PDF 處理庫提供 HTML 到 PDF 轉换、文本和图像注释、PDF 安全、表单填充、压缩和优化等功能。它与 .NET 應用程序兼容,增強了功能性和跨平台兼容性。

如何在 Visual Studio 項目中安装 PDF 處理庫?

可以使用 NuGet 軟件包管理器在 Visual Studio 項目中安装 PDF 處理庫。在包管理终端使用適当的命令或在 NuGet 軟件包管理器界面中搜索庫。

IronPDF 可以与 ASP.NET 和 .NET Core 一起使用嗎?

是的,IronPDF 設计為可以無缝集成到 ASP.NET 和 .NET Core 應用中,允許開發者在各個平台上创建、修改和渲染 PDF 文檔。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我