.NET 幫助

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

發佈 2024年6月6日
分享:

簡介

一對是一個簡單的數據結構,用來保存兩個相關的值。它提供了一種方便的方式來捆綁兩個不同的數據。當需要返回兩個值或在使用鍵值關聯時,常常使用對。

在C#中,開發者經常使用元組 (Tuple<T1, T2>) 用於配對值。然而,元組是不可變的,其元素是通過像 Item1 和 Item2 這樣的屬性來訪問的,如果大量使用,可能會導致代碼可讀性降低。這就是自定義 Pair 類派上用場的地方。

如果您需要一個結構來保存兩個相關的物件且資料隱藏不是優先考量,您可以在代碼中使用 Pair 類。Pair 類並不封裝其物件引用,而是直接將它們作為公共類字段暴露給所有調用代碼。

這種設計選擇使得可以直接訪問包含的物件,而不需要封裝的額外開銷。此外,在本文結尾,我們將探討如何 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#

優勢元組

簡潔語法

元組允許您使用簡潔的語法來表達複雜的資料結構,無需定義自訂類別或結構。

輕量級

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

隱式命名

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

從方法返回多個值

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

現在,讓我們透過以下示例來探討一些常見的使用情境,其中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> 在 C# 中

Dictionary<TKey, TValue> 類別在 C# 中是一個用於存儲鍵值對的泛型集合。它根據鍵提供快速查找,廣泛用於管理關聯數據。

建立和填充字典

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 Library

IronPDFIron 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.9 剛剛發布

免費 NuGet 下載 總下載次數: 10,746,704 查看許可證 >