.NET 帮助

C# 参考(开发人员如何使用)

发布 2024年四月29日
分享:

在 C# 中 关键词 是一个强大的功能,允许方法修改传递的引用类型变量的参数值。了解如何使用 ref 可以提高您在应用程序中管理和操作数据的能力。

本文将引导您了解ref关键字的基础知识、应用以及与不同数据类型配合使用时的细微差别。我们还将了解 IronPDF 库 是一个 PDF 库。

了解 ref 参数

ref 参数是一种方法参数,它充当传入方法的变量的引用。与只传递变量副本的标准值参数不同,ref 参数允许被调用的方法修改原始变量的值。当你需要一个方法更新传递给它的变量的状态时,这种行为是至关重要的。

下面的示例*演示了引用的基本用法,重点是*引用类型变量如何在整个方法调用过程中将其参数值保留在同一对象中:

class Program
{
    static void Main()
    {
        int number = 100;
        ModifyNumber(ref number);
        Console.WriteLine(number);
    }
    static void ModifyNumber(ref int number)
    {
        number = 200;
    }
}
class Program
{
    static void Main()
    {
        int number = 100;
        ModifyNumber(ref number);
        Console.WriteLine(number);
    }
    static void ModifyNumber(ref int number)
    {
        number = 200;
    }
}
Friend Class Program
	Shared Sub Main()
		Dim number As Integer = 100
		ModifyNumber(number)
		Console.WriteLine(number)
	End Sub
	Private Shared Sub ModifyNumber(ByRef number As Integer)
		number = 200
	End Sub
End Class
VB   C#

在本例中,Main 方法声明了一个整数 number,并将其初始化为 100。然后调用 ModifyNumber,将 number 作为 ref 参数传递。在 ModifyNumber 中,number 的值被改为 200。由于 number 是通过引用传递的,因此Main 方法中的原始值反映了这一变化,而 200 则被打印到控制台。

ref 参数如何工作

使用ref关键字声明方法参数时,就是告诉编译器该参数将引用原始变量而非副本。这是通过传递变量的内存地址而不是实际值来实现的。被调用的方法和调用的方法都访问相同的内存位置,这意味着对参数所做的任何更改都会直接作用于原始变量。

理解ref的关键在于认识到它既可用于值类型,也可用于引用类型。值类型包括整数和结构体等简单数据类型,而引用类型包括对象和数组。不过,尽管引用类型变量本质上持有内存地址,但在引用类型中使用 ref,可以修改实际引用,而不仅仅是对象的内容。

ref 和 out 之间的区别

虽然refout关键字都允许修改原始变量,但它们之间还是有重要区别的。out 参数在传递给方法之前不需要初始化。相反,ref 参数则要求在传递之前对变量进行初始化。此外,使用out参数的方法有义务在返回之前赋值。这一要求不适用于参考参数。

下面是out关键字的使用方法:

class Program
{
    static void Main()
    {
        int result;
        CalculateResult(out result);
        Console.WriteLine(result);
    }
    static void CalculateResult(out int calculation)
    {
        calculation = 20 * 5;
    }
}
class Program
{
    static void Main()
    {
        int result;
        CalculateResult(out result);
        Console.WriteLine(result);
    }
    static void CalculateResult(out int calculation)
    {
        calculation = 20 * 5;
    }
}
Friend Class Program
	Shared Sub Main()
		Dim result As Integer = Nothing
		CalculateResult(result)
		Console.WriteLine(result)
	End Sub
	Private Shared Sub CalculateResult(ByRef calculation As Integer)
		calculation = 20 * 5
	End Sub
End Class
VB   C#

在这种情况下,CalculateResult 会初始化方法中的计算,而 Main则反映计算结果。

ref 在方法重载中的实际应用

ref也可用于方法重载,即通过ref关键字改变方法签名。方法签名由方法名称和参数类型组成,包括参数是否通过引用传递。 (ref)值,或作为参数。

考虑基于 ref 和值参数重载方法:

class Program
{
    static void Main()
    {
        int normalParameter = 10, refParameter = 10;
        IncrementValue(normalParameter);
        IncrementValue(ref refParameter);
        Console.WriteLine($"Normal: {normalParameter}, Ref: {refParameter}");
    }
    static void IncrementValue(int number)
    {
        number++;
    }
    static void IncrementValue(ref int number)
    {
        number++;
    }
}
class Program
{
    static void Main()
    {
        int normalParameter = 10, refParameter = 10;
        IncrementValue(normalParameter);
        IncrementValue(ref refParameter);
        Console.WriteLine($"Normal: {normalParameter}, Ref: {refParameter}");
    }
    static void IncrementValue(int number)
    {
        number++;
    }
    static void IncrementValue(ref int number)
    {
        number++;
    }
}
Friend Class Program
	Shared Sub Main()
		Dim normalParameter As Integer = 10, refParameter As Integer = 10
		IncrementValue(normalParameter)
		IncrementValue(refParameter)
		Console.WriteLine($"Normal: {normalParameter}, Ref: {refParameter}")
	End Sub
'INSTANT VB TODO TASK: VB does not allow method overloads which differ only in parameter ByVal/ByRef:
'ORIGINAL LINE: static void IncrementValue(int number)
	Private Shared Sub IncrementValue(ByVal number As Integer)
		number += 1
	End Sub
'INSTANT VB TODO TASK: VB does not allow method overloads which differ only in parameter ByVal/ByRef:
'ORIGINAL LINE: static void IncrementValue(ref int number)
	Private Shared Sub IncrementValue(ByRef number As Integer)
		number += 1
	End Sub
End Class
VB   C#

在这里,IncrementValue 被重载,其中一个版本使用普通参数,另一个版本使用ref参数。ref 版本会递增原始变量,而普通版本只会更改副本。

IronPDF 简介

C# Ref(如何为开发人员工作):图 1

IronPDF 是一个全面的 .NET 库,专为处理 PDF 文档而设计。它主要用 C# 编写,重点是简化 PDF 文档的创建和操作。 从 HTML 内容生成 PDF.通过使用 Chrome 浏览器渲染引擎,IronPDF 可提供高质量、像素完美的 PDF 文档,捕捉 HTML、CSS、JavaScript 和图像内容的细微差别。

该库用途广泛,支持包括 .NET Framework、.NET Core 和 .NET Standard 在内的各种 .NET 环境,因此适用于从桌面到基于 Web 系统的各种应用。IronPDF 不仅支持 PDF 创建,还提供编辑、保护和将 PDF 转换为其他格式的功能。

该功能还能提取文本和图像、填写表格,甚至应用数字签名,确保在 .NET 应用程序中全面处理 PDF 文档。

将 IronPDF 与 C&num 整合;以及 ref 关键字

IronPDF 可与 C# 集成,以利用该语言的强大功能,包括使用 ref 关键字通过引用传递参数。这种集成允许动态生成 PDF,其中的内容可能取决于运行时确定值的变量。

为了说明 IronPDF 与 C# 的集成(使用 ref 关键字),请考虑这样一种情况:我们想要生成一份包含动态计算值的 PDF 报告。该值将在一个接受 ref 参数的方法中计算,允许该方法修改该值,然后反映在生成的 PDF 中。

代码示例:使用 ref 生成带有动态内容的 PDF

下面的 C# 代码演示了如何将 IronPDF 与 ref 关键字结合使用以生成 PDF 文档。代码计算一个值,通过一个接受ref参数的方法对其进行修改,然后使用 IronPDF 生成一个包含该动态内容的 PDF。

using IronPdf;
using System;
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // Initialize the value
        int totalSales = 150;
        // Modify the value within the method using 'ref'
        AddMonthlyBonus(ref totalSales);
        // Use IronPDF to generate a PDF report
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf($"<h1>Monthly Sales Report</h1><p>Total Sales, including bonus: {totalSales}</p>");
        // Save the PDF to a file
        PDF.SaveAs("MonthlySalesReport.pdf");
        // Confirm the PDF has been generated
        Console.WriteLine("PDF generated successfully. Check your project directory.");
    }
    static void AddMonthlyBonus(ref int sales)
    {
        // Assume a bonus of 10% of the sales
        sales += (int)(sales * 0.1);
    }
}
using IronPdf;
using System;
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // Initialize the value
        int totalSales = 150;
        // Modify the value within the method using 'ref'
        AddMonthlyBonus(ref totalSales);
        // Use IronPDF to generate a PDF report
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf($"<h1>Monthly Sales Report</h1><p>Total Sales, including bonus: {totalSales}</p>");
        // Save the PDF to a file
        PDF.SaveAs("MonthlySalesReport.pdf");
        // Confirm the PDF has been generated
        Console.WriteLine("PDF generated successfully. Check your project directory.");
    }
    static void AddMonthlyBonus(ref int sales)
    {
        // Assume a bonus of 10% of the sales
        sales += (int)(sales * 0.1);
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		' Initialize the value
		Dim totalSales As Integer = 150
		' Modify the value within the method using 'ref'
		AddMonthlyBonus(totalSales)
		' Use IronPDF to generate a PDF report
		Dim Renderer = New ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf($"<h1>Monthly Sales Report</h1><p>Total Sales, including bonus: {totalSales}</p>")
		' Save the PDF to a file
		PDF.SaveAs("MonthlySalesReport.pdf")
		' Confirm the PDF has been generated
		Console.WriteLine("PDF generated successfully. Check your project directory.")
	End Sub
	Private Shared Sub AddMonthlyBonus(ByRef sales As Integer)
		' Assume a bonus of 10% of the sales
		sales += CInt(Math.Truncate(sales * 0.1))
	End Sub
End Class
VB   C#

C# Ref(如何为开发人员工作):图 2

在本例中,totalSales 的起始值为 150。AddMonthlyBonus方法使用ref关键字引用该值,计算出 10%的奖金,并将其添加到原始销售值中。然后,IronPDF 会生成一个 PDF 文档,其中包含一个 HTML 代码段,报告包括奖金在内的总销售额。最终文档保存为 "MonthlySalesReport.pdf"。

结论

C# Ref(如何为开发人员工作):图 3

了解 C# 中的ref关键字为管理方法之间的数据传递方式提供了一个有价值的工具。通过允许方法直接修改传递给它们的参数的原始值,ref 可以使你的方法更加灵活和强大。

随着ref使用经验的积累,您将更好地了解何时以及如何有效地使用ref来满足您的编程需求。IronPDF 提供 免费试用 749 美元起。

< 前一页
MS Graph .NET(开发人员如何使用)
下一步 >
Mudblazor .NET 8(对开发人员的工作方式)

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

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