.NET 幫助

C# Pair 類 (對開發人員的運作方式)

發佈 2024年6月6日
分享:

介紹

一对是一个简单的数据结构,用于存放两个相关的值。 它提供了一種方便的方法將兩個不同的數據組合在一起。 當一個方法需要返回兩個值或者在處理鍵值關聯時,通常使用對組。

在 C# 中,開發人員通常會使用元組(Tuple<T1, T2>)用於配對值。 然而,元组是不可变的,其元素通过类似 Item1 和 Item2 的属性访问,当被大量使用时可能会导致代码的可读性降低。 這就是自訂 Pair 類別派上用場的地方。

如果您需要一個結構來保存兩個相關的對象且數據隱藏不是優先考慮的問題,您可以在代碼中使用 Pair 類。 Pair 類別不封裝其物件參照。 相反,它直接將它們作為公共類字段暴露給所有呼叫代碼。

此設計選擇允許在不需封裝開銷的情況下直接訪問包含的對象。 此外,在文章的最後,我們將探討如何IronPDF 用於生成 PDFIron 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#

元組的優勢

简洁语法

元組允許您使用簡潔的語法表達複雜的數據結構,而無需定義自定義類或結構。

輕量級

元組是輕量級數據結構,適用於需要臨時或中間數據存儲的情境。

隱式命名

使用元組語法,您可以隱式命名元組元素,增強代碼的可讀性並減少註釋的需求。

從方法返回多個值

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 等來存取 Tuple 元素,這可能會降低程式碼的可讀性。

自訂類別配對

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 類別

現在,讓我們在以下範例中探索一些 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 by Iron Software 產品是一個優秀的用於生成 PDF 文件的庫。 它的易用性和效率無與倫比。

IronPDF 可以從 NuGet 套件管理器安裝:

Install-Package IronPdf

或者從 Visual Studio 這樣做:

C# Pair 類別(開發人員如何使用):圖 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,622,374 查看許可證 >