.NET Framework 4.0 引入 `System.Tuple` 類別,提供**固定大小、不可變、可序列化**的多元素資料結構。它解決了方法需返回多個值、避免建立大量單用途 DTO 類別的問題。本文詳細說明 Tuple 建立、存取、巢狀、解構 (C# 7+)、ValueTuple 結構體版本、效能比較與實務應用場景。
var person = Tuple.Create(1, "張三", 25, true); // Tuple
int id = person.Item1; // 1
string name = person.Item2; // "張三"
int age = person.Item3; // 25
bool isActive = person.Item4; // true
var tuple = new Tuple(100, "訂單", DateTime.Now);
// 8 個以上需巢狀在第 8 位置
var many = Tuple.Create(1,2,3,4,5,6,7, Tuple.Create(8,9,10));
int ninth = many.Rest.Item1; // 8
// 傳統 out 參數
public bool TryParseOld(string input, out int result, out string error) { ... }
// Tuple 版本:清晰、可讀、支援非同步
public Tuple TryParseNew(string input)
{
if (int.TryParse(input, out int val))
return Tuple.Create(true, val, (string)null);
return Tuple.Create(false, 0, "格式錯誤");
}
// 呼叫
var result = TryParseNew("123");
if (result.Item1) Console.WriteLine($"值: {result.Item2}");
else Console.WriteLine($"錯誤: {result.Item3}");
// LINQ 分組鍵為多欄位
var groups = orders.GroupBy(o => Tuple.Create(o.CustomerId, o.OrderDate.Month))
.Select(g => new { g.Key.Item1, g.Key.Item2, Count = g.Count() });
// Dictionary 鍵為複合鍵
var dict = new Dictionary, decimal>();
dict[Tuple.Create(1, "USD")] = 30.5m;
// 不想建立 class PersonDto { Id, Name, Age }
var persons = new List>
{
Tuple.Create(1, "Alice", 30),
Tuple.Create(2, "Bob", 25)
};
.NET 4.7+ / .NET Core / .NET 5+ 內建 `System.ValueTuple` 結構體,**效能更好 (避免堆積配置)、支援命名元素、解構語法**。
// 建立
(string Name, int Age, bool Active) person = ("Alice", 30, true);
// 或
var person = (Name: "Alice", Age: 30, Active: true);
// 存取:IntelliSense 支援名稱
Console.WriteLine($"{person.Name}, {person.Age}"); // 不需 Item1, Item2
public (bool Success, int Value, string Error) TryParse(string input)
{
if (int.TryParse(input, out int val))
return (true, val, null);
return (false, 0, "格式錯誤");
}
// 呼叫端解構
var (success, value, error) = TryParse("123");
if (success) Console.WriteLine(value);
else Console.WriteLine(error);
public class Point { public int X; public int Y;
public void Deconstruct(out int x, out int y) { x = X; y = Y; } }
var (x, y) = new Point { X = 10, Y = 20 }; // 直接解構
| 特性 | Tuple (Class) | ValueTuple (Struct) |
|---|---|---|
| 型別 | 參考型別 | 實值型別 |
| 記憶體 | 堆積配置、GC 壓力 | 堆疊/內嵌、無 GC |
| 可變性 | 不可變 | 可變 (欄位可寫入) |
| 命名元素 | 不支援 (僅 Item1...) | 支援 (編譯器魔法) |
| 解構語法 | 不支援 | 支援 |
| 序列化 | 原生支援 | 需自訂或升級序列化器 |
| Null | 可為 null | 不可為 null (除非可為 null 型別) |
| 適用 .NET 版本 | 4.0+ | 4.7+ / .NET Core / .NET 5+ |
// Tuple: ~1.8 秒, 記憶體配置 ~2.4 GB
// ValueTuple: ~0.6 秒, 記憶體配置 ~0 GB (堆疊)
結論:新專案 (.NET 4.7+/Core/5+) **一律使用 ValueTuple**。舊專案 (.NET 4.0-4.6.2) 僅能用 Tuple,或透過 NuGet 安裝 `System.ValueTuple` 套件使用 ValueTuple。
// ValueTuple 可直接作 Key (結構體值相等性)
var dict = new Dictionary<(int, string), object>();
dict[(1, "A")] = "Value";
public async Task<(bool Success, T Data, string Error)> GetDataAsync(int id)
{
try { var data = await repo.GetAsync(id); return (true, data, null); }
catch (Exception ex) { return (false, default, ex.Message); }
}
public static class TupleExtensions
{
public static (T1, T2) ToTuple(this (T1, T2) t) => t; // 無意義,僅示範
}
總結:.NET 4.0 `Tuple` 解決了多返回值與臨時資料結構需求,但作為參考型別有效能開銷且無命名支援。**現代開發 (.NET 4.7+/Core/5+) 應全面改用 `ValueTuple` (元組語法糖)**,享有命名元素、解構、堆疊配置、高效能等優勢。僅在維護舊版專案或需序列化相容時使用 `Tuple`。善用元組簡化程式碼,但避免濫用取代領域模型。