IRONSOFTWAREHOME
开发者更新

C# Pair类(开发人员如何使用)

Jacob Mellor,Team Iron 的首席技术官
Jacob Mellor
Updated: 2026年4月23日

对。 它提供了一种将两个不同数据片段捆绑在一起的便捷方法。 当方法需要返回两个值或处理键值关联时,通常会使用成对。

在C#中,开发者经常使用元组(Tuple<T1, T2>)来配对值。 然而,元组是不可变的,其元素是通过Item1和Item2这样的属性访问的,这可能在大量使用时导致代码的可读性降低。 这就是自定义Pair类的用武之地。

如果您需要一个结构来保存两个相关对象且数据隐藏不是优先事项,您可以在代码中使用Pair类。 Pair类不会封装其对象引用。 相反,它将它们直接作为公共类字段暴露给所有调用代码。

这种设计选择允许无需封装开销即可简单直接地访问包含的对象。 此外,在文章的最后,我们将探讨如何使用 IronPDF 进行 PDF 生成 来生成 PDF 文档,这来自 Iron Software 概览。

元组

C# 7.0引入了元组语法改进,使元组的使用更加便捷。 以下是如何声明和初始化元组的方法:

// Tuple declaration
var person = (name: "John", age: 30);

// Accessing tuple elements using named properties
Console.WriteLine($"Name: {person.name}, Age: {person.age}");

// Tuple deconstruction
var (name, age) = person;
Console.WriteLine($"Name: {name}, Age: {age}");

元组的优点

简明的语法

元组允许您使用简明的语法表达复杂的数据结构,而无需定义自定义类或结构。

轻量级

元组是轻量级的数据结构,非常适用于需要临时或中间数据存储的场景。

隐式命名

通过元组语法,您可以隐式地命名元组元素,增加代码的可读性并减少对注释的需求。

从方法返回多个值

public (int Quotient, int Remainder) Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return (quotient, remainder);
}

var result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.Quotient}, Remainder: {result.Remainder}");

简化方法签名

public (string Name, string Surname) GetNameAndSurname()
{
    // Retrieve name and surname from a data source
    return ("John", "Doe");
}

var (name, surname) = GetNameAndSurname();
Console.WriteLine($"Name: {name}, Surname: {surname}");

分组相关数据

var point = (x: 10, y: 20);
var color = (r: 255, g: 0, b: 0);
var person = (name: "Alice", age: 25);

限制和注意事项

虽然C# 7.0元组提供了显著的优势,但仍需注意以下限制和注意事项:

  • 与自定义类或结构相比,元组在表达能力上有限。
  • 当没有提供显式名称时,元组元素通过Item1、Item2等访问,这可能降低代码的可读性。

Pair自定义类

public class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }

    // Constructor to initialize the pair
    public Pair(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}

在这个类中,类型在使用时定义,并且这两个属性作为公共属性暴露。

使用Pair类

现在,让我们探讨一些Pair类可以受益的常见用例:

1. 存储坐标

// Creating a new instance of the Pair class to store coordinates
Pair<int, int> coordinates = new Pair<int, int>(10, 20);
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}");

2. 从方法返回多个值

// Method returning a Pair, representing both quotient and remainder
public Pair<int, int> Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return new Pair<int, int>(quotient, remainder);
}

// Usage
Pair<int, int> result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}");

3. 存储键值对

// Storing a key-value pair
Pair<string, int> keyValue = new Pair<string, int>("Age", 30);
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}");

键值对

键值对提供了一种简单高效的数据关联方式。 在C#中,处理键值对的主要工具是Dictionary<TKey, TValue>类,它是一种多功能且强大的集合类型。

理解键值对

键值对是一种将唯一键和一个值关联的数据结构。 这种关联允许基于唯一标识符高效检索和操作数据。 在C#中,键值对通常用于缓存、配置管理和数据存储等任务。

Dictionary<TKey, TValue> in C#

C#中的Dictionary<TKey, TValue>类是一个通用集合,用于存储键值对。 它提供基于键的快速查找,并广泛用于管理关联数据。

创建和填充字典

Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 35 },
    { "Charlie", 25 }
};

按键访问值

// Directly access a value by its key
Console.WriteLine($"Alice's age: {ages["Alice"]}");

迭代键值对

// Iterate over all key-value pairs in the dictionary
foreach (var pair in ages)
{
    Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}

高级场景

处理缺失键

if (ages.TryGetValue("David", out int age))
{
    Console.WriteLine($"David's age: {age}");
}
else
{
    Console.WriteLine("David's age is not available.");
}

删除条目

// Remove an entry given its key
ages.Remove("Charlie");

字典初始化

// Initialize a dictionary with color codes
var colors = new Dictionary<string, string>
{
    { "red", "#FF0000" },
    { "green", "#00FF00" },
    { "blue", "#0000FF" }
};

超越字典:替代方案和考虑事项

虽然Dictionary<TKey, TValue>是一个强大的工具,但替代方法和考虑因素取决于您的应用程序的具体要求:

  • ConcurrentDictionary<TKey, TValue>。
  • ImmutableDictionary<TKey, TValue>提供不可变的键值集合。
  • 自定义键值对类:在需要额外功能或特定行为的情况下,考虑创建自定义键值对类以满足您的需求。

IronPDF库

Iron Software产品的IronPDF 是一个用于生成PDF文档的优秀库。 它的易用性和高效性无与伦比。

IronPDF在HTML到PDF转换方面表现出色,确保精确保留原始布局和样式。 它非常适合从基于Web的内容中创建PDF,如报告、发票和文档。 利用对HTML文件、URL和原始HTML字符串的支持,IronPDF轻松生成高质量的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");
    }
}

可以从NuGet包管理器安装IronPDF:

PM > Install-Package IronPdf

或者从Visual Studio这样:

C#配对类(开发者如何使用):图1 - 使用NuGet包管理器安装IronPDF

要生成一个具有元组示例的文档,我们可以使用以下代码:

using IronPdf;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // var pattern
            var content = "<h1>Iron Software is Awesome</h1> Made with IronPDF!";
            content += "<h2>Demo C# Pair with Tuples</h2>";

            var result = Divide(10, 3);
            Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}");
            content += $"<p>When we divide 10 by 3:</p>";
            content += $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content);
            pdf.SaveAs("output.pdf"); // Saves PDF
        }

        // Method to demonstrate division using tuples
        public static (int Quotient, int Remainder) Divide(int dividend, int divisor)
        {
            int quotient = dividend / divisor;
            int remainder = dividend % divisor;
            return (quotient, remainder);
        }
    }
}

输出

C#配对类(开发者如何使用):图2

IronPDF的试用许可证

获取您的IronPDF试用许可证并将许可证放置在appsettings.json中。

{
    "IronPdf.LicenseKey": "<Your Key>"
}
JSON

结论

在本文中,我们探讨了配对的概念以及在C#中拥有一个Pair类的重要性。 我们提供了一个简单的Pair自定义类实现,以及各种用例,展示了其在日常编程任务中的多功能性和实用性。

无论您是在处理坐标、从方法返回多个值,还是存储键值关联,Pair类都可以成为您编程技能的一个有价值的补充。

除此之外,IronPDF库功能是开发人员需要在应用程序中即时生成PDF文档的一个不错的技能组合。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥。

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

OR
bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥。
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索 “IronPDF”
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

或在此处下载 Windows 安装程序。

  1. 下载并解压 IronPDF 到您的解决方案目录中的 ~/Libs 之类的位置
  2. 在 Visual Studio 解决方案资源管理器中,右键点击引用。选择浏览,“IronPDF.dll”

$999 起