.NET 帮助

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

发布 2024年六月6日
分享:

介绍

数据对是一种简单的数据结构,用于保存两个相关的值。 它提供了一种将两个不同的数据捆绑在一起的便捷方式。 当一个方法需要返回两个值或处理键值关联时,通常会用到对。

在 C# 中,开发人员经常使用元组(元组<T1, T2>`)用于配对值。 但是,元组是不可变的,其元素通过 Item1 和 Item2 等属性进行访问,如果大量使用,可能会导致代码的可读性降低。 这就是自定义 Pair 类的用武之地。

如果您需要一个结构来容纳两个相关对象,并且数据隐藏不是优先考虑的问题,您可以在代码中使用 Pair 类。 Pair 类没有封装其对象引用。 在翻译过程中,译者不能将这些工具作为公共类的字段,而是将它们作为公共类字段直接暴露给所有调用代码。

这种设计选择允许直接访问所包含的对象,而不会产生封装的开销。 此外,在文章的最后,我们将探讨如何用于生成 PDF 的 IronPDFIron Software 概述可用于生成 PDF 文档。

元组

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

// Tuple declaration
var person = (name: "John", age: 30);
// Accessing tuple elements
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
Console.WriteLine($"Name: {person.name}, Age: {person.age}");
// Tuple deconstruction
var (name, age) = person;
Console.WriteLine($"Name: {name}, Age: {age}");
' Tuple declaration
Dim person = (name:= "John", age:= 30)
' Accessing tuple elements
Console.WriteLine($"Name: {person.name}, Age: {person.age}")
' Tuple deconstruction
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
var(name, age) = person
Console.WriteLine($"Name: {name}, Age: {age}")
VB   C#

元组的优点

简洁的语法

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

轻量级

Tuples 是一种轻量级数据结构,适用于需要临时或中间存储数据的场景。

隐式命名

使用元组语法,您可以隐式命名元组元素,从而提高代码的可读性并减少注释的需要。

从方法中返回多个值

public (int, int) 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.Item1}, Remainder: {result.Item2}");
public (int, int) 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.Item1}, Remainder: {result.Item2}");
Public Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As (Integer, Integer)
	Dim quotient As Integer = dividend \ divisor
	Dim remainder As Integer = dividend Mod divisor
	Return (quotient, remainder)
End Function
Private result = Divide(10, 3)
Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}")
VB   C#

简化方法签名

public (string, string) GetNameAndSurname()
{
    // Retrieve name and surname from a data source
    return ("John", "Doe");
}
var (name, surname) = GetNameAndSurname();
Console.WriteLine($"Name: {name}, Surname: {surname}");
public (string, string) GetNameAndSurname()
{
    // Retrieve name and surname from a data source
    return ("John", "Doe");
}
var (name, surname) = GetNameAndSurname();
Console.WriteLine($"Name: {name}, Surname: {surname}");
Public Function GetNameAndSurname() As (String, String)
	' Retrieve name and surname from a data source
	Return ("John", "Doe")
End Function
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
var(name, surname) = GetNameAndSurname()
Console.WriteLine($"Name: {name}, Surname: {surname}")
VB   C#

分组相关数据

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);
Dim point = (x:= 10, y:= 20)
Dim color = (r:= 255, g:= 0, b:= 0)
Dim person = (name:= "Alice", age:= 25)
VB   C#

限制和注意事项

虽然 C# 7.0 图元具有显著的优势,但也有一些限制和注意事项需要牢记:

  • 与自定义类或结构体相比,元组的表达能力有限。
  • 在没有提供明确名称的情况下,元组元素使用 Item1、Item2 等进行访问,这会降低代码的可读性。

配对自定义类

public class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }
    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; }
    public Pair(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}
Public Class Pair(Of T1, T2)
	Public Property First() As T1
	Public Property Second() As T2
	Public Sub New(ByVal first As T1, ByVal second As T2)
		Me.First = first
		Me.Second = second
	End Sub
End Class
VB   C#

这里的类型是在使用时定义的,两个属性是作为公共属性公开的。

使用配对类

现在,让我们在下面的示例中探讨一些常见的使用案例,看看 Pair 类在这些案例中的作用:

1.存储坐标

Pair<int, int> coordinates = new Pair<int, int>(10, 20); // new instance
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}");
Pair<int, int> coordinates = new Pair<int, int>(10, 20); // new instance
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}");
Dim coordinates As New Pair(Of Integer, Integer)(10, 20) ' new instance
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}")
VB   C#

2.从方法中返回多个值

public Pair<int, int> Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return new Pair<int, int>(quotient, remainder);
}
Pair<int, int> result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}");
public Pair<int, int> Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return new Pair<int, int>(quotient, remainder);
}
Pair<int, int> result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}");
Public Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As Pair(Of Integer, Integer)
	Dim quotient As Integer = dividend \ divisor
	Dim remainder As Integer = dividend Mod divisor
	Return New Pair(Of Integer, Integer)(quotient, remainder)
End Function
Private result As Pair(Of Integer, Integer) = Divide(10, 3)
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}")
VB   C#

3.存储键值对

Pair<string, int> keyValue = new Pair<string, int>("Age", 30);
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}");
Pair<string, int> keyValue = new Pair<string, int>("Age", 30);
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}");
Dim keyValue As New Pair(Of String, Integer)("Age", 30)
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}")
VB   C#

键值对

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

理解键值对

键值对是一种将唯一的键与值关联起来的数据结构。 这种关联可以根据数据的唯一标识符对数据进行有效检索和操作。 在 C# 中,键值对常用于缓存、配置管理和数据存储等任务。

C# 中的 Dictionary<TKey, TValue>

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

创建和填充字典

Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 35;
ages["Charlie"] = 25;
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 35;
ages["Charlie"] = 25;
Dim ages As New Dictionary(Of String, Integer)()
ages("Alice") = 30
ages("Bob") = 35
ages("Charlie") = 25
VB   C#

按键访问值

Console.WriteLine($"Alice's age: {ages["Alice"]}");
Console.WriteLine($"Alice's age: {ages["Alice"]}");
Console.WriteLine($"Alice's age: {ages("Alice")}")
VB   C#

键值对迭代

foreach (var pair in ages)
{
    Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}
foreach (var pair in ages)
{
    Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}
For Each pair In ages
	Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}")
Next pair
VB   C#

高级场景

处理丢失的密钥

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.");
}
Dim age As Integer
If ages.TryGetValue("David", age) Then
	Console.WriteLine($"David's age: {age}")
Else
	Console.WriteLine("David's age is not available.")
End If
VB   C#

删除条目

ages.Remove("Charlie");
ages.Remove("Charlie");
ages.Remove("Charlie")
VB   C#

字典初始化

var colors = new Dictionary<string, string>
{
    { "red", "#FF0000" },
    { "green", "#00FF00" },
    { "blue", "#0000FF" }
};
var colors = new Dictionary<string, string>
{
    { "red", "#FF0000" },
    { "green", "#00FF00" },
    { "blue", "#0000FF" }
};
Dim colors = New Dictionary(Of String, String) From {
	{"red", "#FF0000"},
	{"green", "#00FF00"},
	{"blue", "#0000FF"}
}
VB   C#

词典之外:替代方案和考虑因素

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

  • ConcurrentDictionary<TKey,TValue>:如果您的应用程序需要从多个线程对字典进行线程安全访问,请考虑使用ConcurrentDictionary<TKey,TValue>`。
  • ImmutableDictionary<TKey,TValue>:对于需要不可变性的场景,System.Collections.Immutable命名空间中的ImmutableDictionary<TKey,TValue>`提供了不可变的键值集合。
  • 自定义键值对类:在您需要额外功能或特定行为的情况下,可以考虑根据您的要求创建自定义键值对类。

IronPDF 库

IronPDF 由 Iron Software Products 提供是一个生成 PDF 文档的优秀库。 其易用性和效率首屈一指。

IronPdf 可通过 NuGet 软件包管理器安装:

Install-Package IronPdf

或者从 Visual Studio 这样翻译:

C# 对类(如何为开发人员工作):图 1 - 使用 NuGet 软件包管理器安装 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, 3 </p>";
        content += $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>";
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs("output.pdf"); // Saves PDF        
    }
    public static (int, int) Divide(int dividend, int divisor)
    {
        // var count;
        int quotient = dividend / divisor;
        int remainder = dividend % divisor;
        return (quotient, remainder);
    }
}
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, 3 </p>";
        content += $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>";
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs("output.pdf"); // Saves PDF        
    }
    public static (int, int) Divide(int dividend, int divisor)
    {
        // var count;
        int quotient = dividend / divisor;
        int remainder = dividend % divisor;
        return (quotient, remainder);
    }
}
Namespace IronPatterns
	Friend Class Program
		Shared Sub Main()
			Console.WriteLine("-----------Iron Software-------------")
			Dim renderer = New ChromePdfRenderer() ' var pattern
			Dim content = " <h1> Iron Software is Awesome </h1> Made with IronPDF!"
			content &= "<h2>Demo C# Pair with Tuples</h2>"
			Dim result = Divide(10, 3)
			Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}")
			content &= $"<p>When we divide 10, 3 </p>"
			content &= $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>"
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			pdf.SaveAs("output.pdf") ' Saves PDF
		End Sub
		Public Shared Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As (Integer, Integer)
			' var count;
			Dim quotient As Integer = dividend \ divisor
			Dim remainder As Integer = dividend Mod divisor
			Return (quotient, remainder)
		End Function
	End Class
End Namespace
VB   C#

输出

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

IronPDF 试用许可证

获取您的IronPDF 试用许可证并将许可证放入 appsettings.json

"IronPDF.LicenseKey": "<Your Key>"
"IronPDF.LicenseKey": "<Your Key>"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPDF.LicenseKey": "<Your Key>"
VB   C#

结论

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

无论您是要处理坐标、从方法中返回多个值,还是要存储键值关联,Pair 类都是您编程技能的宝贵补充。

除此以外IronPDF 库功能对于开发人员来说,在应用程序中根据需要即时生成 PDF 文档是一项非常重要的组合技能。

< 前一页
内部关键字C#(对开发者的工作原理)
下一步 >
Dapper C#(它如何为开发人员工作)

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

免费NuGet下载 总下载量: 11,781,565 查看许可证 >