.NET ヘルプ

C#ペアクラス(開発者向けの仕組み)

更新済み 6月 6, 2024
共有:

イントロダクション

ペアは、2つの関連する値を保持するシンプルなデータ構造です。 それは、2つの異なるデータの断片をまとめる便利な方法を提供します。 メソッドが2つの値を返す必要がある場合や、キーと値の関連を扱う際に、ペアはよく使用されます。

C#では、開発者はしばしばタプルを使用します (Tuple<T1, T2>) 値のペアリング用。 ただし、タプルは不変であり、その要素は Item1 や Item2 のようなプロパティを通じてアクセスされますが、これを多用するとコードの可読性が低下する可能性があります。 これはカスタムPairクラスが役立つところです。

もし2つの関連するオブジェクトを保持する構造が必要であり、データ隠蔽が優先事項でない場合、コード内で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#

ここでは、使用時に型が定義され、2つのプロパティはパブリックなpainプロパティとして公開されています。

ペアクラスの使用

ペアクラスは、2つの関連するオブジェクトを一緒に格納するための簡単な方法を提供します。よく使用される例としては、キーと値のペア、名前と年齢のペア、カテゴリ識別子とカテゴリ名のペアなどがあります。

ペアオブジェクトを作成する方法:

Pair<String, Integer> pair = new Pair<>("名前", 25);
JAVA

この例では、キーは文字列「名前」で値は整数25です。

ペア内の値にアクセスするには、getKey()およびgetValue()メソッドを使用します:

String key = pair.getKey(); // "名前"
Integer value = pair.getValue(); // 25
JAVA

ペアクラスは特に、データベースやリストからのデータの一時的な格納や転送が必要な場合に有用です。

それでは、Pairクラスが有益となるいくつかの一般的な使用例を以下に探ってみましょう。

座標の保存

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#

メソッドから複数の値を返す

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#

キー値ペアの保存

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 から アイアンソフトウェア は、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.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >