.NET 帮助

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

发布 2024年六月6日
分享:

简介

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

在 C# 中,开发人员经常使用元组 (元组<T1, T2>`) 来配对值。然而,元组是不可变的,其元素可通过 Item1 和 Item2 等属性进行访问,这可能导致大量使用时代码的可读性降低。这时,自定义 Pair 类就派上用场了。

如果你需要一个结构来容纳两个相关的对象,而数据隐藏又不是首要任务,那么你就可以在代码中使用 Pair 类。Pair 类并不封装其对象引用。相反,它将对象引用作为公共类字段直接暴露给所有调用代码。

这种设计选择允许直接访问所包含的对象,而不需要封装的开销。此外,在文章的最后,我们将探讨如何 IronPDF铁软件 可用于生成 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#

效益元组

简明语法

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

重量轻

元组是一种轻量级数据结构,适用于需要临时或中间存储数据的情况。

隐式命名

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

从方法中返回多个值

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# 中,键值对通常用于缓存、配置管理和数据存储等任务。

Dictionary<TKey, TValue> in C&num;

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铁软件 是一个用于生成 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.10 刚刚发布

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