C# Pair类(开发人员如何使用)
对。 它提供了一种将两个不同数据片段捆绑在一起的便捷方法。 当方法需要返回两个值或处理键值关联时,通常会使用成对。
在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}");// 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 (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}");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);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;
}
}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}");// 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}");// 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}");// 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>在C#
C#中的Dictionary<TKey, TValue>类是一个泛型集合,用于存储键值对。 它提供基于键的快速查找,并广泛用于管理关联数据。
创建和填充字典
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 35 },
{ "Charlie", 25 }
};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"]}");// 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}");
}// 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.");
}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");// 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" }
};// Initialize a dictionary with color codes
var colors = new Dictionary<string, string>
{
{ "red", "#FF0000" },
{ "green", "#00FF00" },
{ "blue", "#0000FF" }
};超越字典:替代方案和考虑事项
虽然Dictionary<TKey, TValue>是一个强大的工具,替代方法和注意事项取决于应用程序的具体需求:
ConcurrentDictionary<TKey, TValue>:如果您的应用程序需要受线程安全的字典访问,请考虑使用ConcurrentDictionary<TKey, TValue>。ImmutableDictionary<TKey, TValue>:对于需要不变性的场景,System.Collections.Immutable命名空间提供的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");
}
}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:
Install-Package IronPdf
或者从Visual Studio这样:

要生成一个具有元组示例的文档,我们可以使用以下代码:
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);
}
}
}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);
}
}
}输出

IronPDF的试用许可证
获取您的IronPDF试用许可证并将许可证放置在appsettings.json中。
{
"IronPDF.LicenseKey": "<Your Key>"
}结论
在本文中,我们探讨了配对的概念以及在C#中拥有一个Pair类的重要性。 我们提供了一个简单的Pair自定义类的实现,以及展示其多功能性和实用性的各种使用案例。
无论您是在处理坐标、从方法返回多个值,还是存储键值关联,Pair类都可以成为您编程技能的一个有价值的补充。
除此之外,IronPDF库功能是开发人员需要在应用程序中即时生成PDF文档的一个不错的技能组合。
常见问题解答
C# 中的 Pair 类是什么?
C# 中的 Pair 类是一个简单的数据结构,旨在保存两个相关的值。它允许通过公共字段直接访问其属性,当封装不是优先事项时,这是元组的一个方便替代方案。
Pair 类与 C# 中的元组有何不同?
Pair 类与元组的不同之处在于它通过公共字段直接暴露其对象引用,增强了可读性和灵活性。而元组是不可变的,通过像 Item1 和 Item2 这样的属性访问其元素。
使用 Pair 类相对于元组的优势是什么?
使用 Pair 类相对于元组的优势包括使用描述性的属性名称而不是 Item1 和 Item2 来提高代码可读性,并且可以修改值,因为 Pairs 是可变的。
我可以使用 Pair 类来存储键值对吗?
是的,Pair 类特别适用于以比元组更具可读性的方式存储键值对,因为它可以通过公共字段直接访问值。
使用 Pair 类的常见场景是什么?
使用 Pair 类的常见场景包括存储坐标、从方法返回多个值以及以可读的格式管理键值对关联。
开发人员为什么会选择使用 IronPDF 库?
开发人员可能会选择使用 IronPDF 库将 HTML 内容生成 PDF。它确保保留原始布局和样式,简化如报告和发票等专业文档的创建。
如何在 C# 中从 HTML 文件生成 PDF?
您可以使用 IronPDF 库在 C# 中从 HTML 文件生成 PDF。它提供诸如 RenderHtmlAsPdf 之类的方法来将 HTML 字符串和文件转换为高质量的 PDF 文档。
使用库生成PDF有什么好处?
使用像 IronPDF 这样的库进行 PDF 生成提供了简化的过程,确保从各种内容来源准确保留布局和样式,从而创建高质量 PDF 文档。
Pair 类和 IronPDF 库在开发者工具包中扮演什么角色?
Pair 类和 IronPDF 库通过提供使用 Pairs 的有效数据结构管理和使用 IronPDF 的可靠文档生成功能,增强了开发者工具包,使其对处理复杂数据和文档工作流非常有价值。








