Giới thiệu
Tuple (System.Tuple) là kiểu tham chiếu immutable chứa số lượng cố định phần tử (1-8). Truy xuất phần tử qua property Item1...Item7 và Rest (cho Tuple 8 phần tử).
Ví dụ 1: Tuple 7 phần tử (Item4)
using System;
public class Demo
{
public static void Main(string[] args)
{
var tuple1 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500);
var tuple2 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500);
Console.WriteLine($"Tuple1 == Tuple2? {tuple1.Equals(tuple2)}"); // True
Console.WriteLine($"HashCode Tuple1: {tuple1.GetHashCode()}");
Console.WriteLine($"HashCode Tuple2: {tuple2.GetHashCode()}");
Console.WriteLine($"\nTuple1.Item1 (1st): {tuple1.Item1}");
Console.WriteLine($"Tuple1.Item4 (4th): {tuple1.Item4}"); // 700
Console.WriteLine($"Tuple1.Item5 (5th): {tuple1.Item5}"); // 100
}
}
Kết quả
Tuple1 == Tuple2? True
HashCode Tuple1: 3231587
HashCode Tuple2: 3231587
Tuple1.Item1 (1st): 75
Tuple1.Item4 (4th): 700
Tuple1.Item5 (5th): 100
Ví dụ 2: Tuple 8 phần tử (có Rest)
using System;
public class Demo
{
public static void Main(string[] args)
{
// Tuple.Create với 8 args -> Tuple>
var tuple = Tuple.Create(1200, 1500, 2200, 2700, 3100, 3500, 4500, 5500);
Console.WriteLine($"HashCode: {tuple.GetHashCode()}");
Console.WriteLine($"Item1: {tuple.Item1}"); // 1200
Console.WriteLine($"Item2: {tuple.Item2}"); // 1500
Console.WriteLine($"Item3: {tuple.Item3}"); // 2200
Console.WriteLine($"Item4: {tuple.Item4}"); // 2700
Console.WriteLine($"Item5: {tuple.Item5}"); // 3100
Console.WriteLine($"Item6: {tuple.Item6}"); // 3500
Console.WriteLine($"Item7: {tuple.Item7}"); // 4500
Console.WriteLine($"Rest (Item8): {tuple.Rest.Item1}"); // 5500
}
}
Kết quả
HashCode: 49989024
Item1: 1200
Item2: 1500
Item3: 2200
Item4: 2700
Item5: 3100
Item6: 3500
Item7: 4500
Rest (Item8): 5500
ValueTuple (C# 7.0+) - Khuyến nghị dùng thay thế
// Cú pháp ngắn gọn, hiệu năng tốt hơn (struct), có tên thành phần
var person = (Name: "Alice", Age: 30, City: "Hanoi", Score: 9.5);
Console.WriteLine($"Tên: {person.Name}"); // Alice
Console.WriteLine($"Tuổi: {person.Age}"); // 30
Console.WriteLine($"Thành phố: {person.City}"); // Hanoi
Console.WriteLine($"Điểm: {person.Score}"); // 9.5
// Deconstruction
var (name, age, city, score) = person;
So sánh Tuple vs ValueTuple
| Đặc điểm | Tuple (Class) | ValueTuple (Struct) |
|---|---|---|
| Kiểu | Reference type | Value type |
| Hiệu năng | Heap allocation | Stack, no GC |
| Mutable | Immutable | Mutable (có thể gán Item1...) |
| Tên thành phần | Không (Item1...) | Có (named elements) |
| Số phần tử max | 8 (lồng nhau cho hơn) | Không giới hạn thực tế |
Lưu ý
- Tuple chủ yếu dùng cho interop với old API (.NET Framework 4.0-).
- Code mới: **luôn dùng ValueTuple** (using System; hoặc System.ValueTuple NuGet cho old TFM).