ใน C# คลาส Tuple มีเมธอด GetType() ที่คืนค่า Type object แสดง signature ของ tuple รวมถึง nested tuple ได้ เมธอดนี้มาจาก object.GetType() แสดงประเภทที่แท้จริงของอินสแตนซ์
ตัวอย่างโค้ดที่ 1: Nested Tuple
using System;
public class Demo
{
public static void Main(string[] args)
{
var tuple1 = Tuple.Create(150, 1500, Tuple.Create(50, 100));
var tuple2 = Tuple.Create(150, 1500, Tuple.Create(100, 200));
Console.WriteLine("Is Tuple1 equal to Tuple2? = " + tuple1.Equals(tuple2));
Console.WriteLine("HashCode of Tuple1 = " + tuple1.GetHashCode());
Console.WriteLine("Type of Tuple1 = " + tuple1.GetType());
Console.WriteLine("HashCode of Tuple2 = " + tuple2.GetHashCode());
Console.WriteLine("Type of Tuple2 = " + tuple2.GetType());
}
}
ผลลัพธ์
Is Tuple1 equal to Tuple2? = False
HashCode of Tuple1 = 188892
Type of Tuple1 = System.Tuple`3[System.Int32,System.Int32,System.Tuple`2[System.Int32,System.Int32]]
HashCode of Tuple2 = 191462
Type of Tuple2 = System.Tuple`3[System.Int32,System.Int32,System.Tuple`2[System.Int32,System.Int32]]
ตัวอย่างโค้ดที่ 2: Tuple 2 สมาชิก
using System;
public class Demo
{
public static void Main(string[] args)
{
var tuple1 = Tuple.Create(10, 20);
var tuple2 = Tuple.Create(30, 40);
Console.WriteLine("Is Tuple1 equal to Tuple2? = " + tuple1.Equals(tuple2));
Console.WriteLine("HashCode of Tuple1 = " + tuple1.GetHashCode());
Console.WriteLine("Type of Tuple1 = " + tuple1.GetType());
Console.WriteLine("HashCode of Tuple2 = " + tuple2.GetHashCode());
Console.WriteLine("Type of Tuple2 = " + tuple2.GetType());
}
}
ผลลัพธ์
Is Tuple1 equal to Tuple2? = False
HashCode of Tuple1 = 350
Type of Tuple1 = System.Tuple`2[System.Int32,System.Int32]
HashCode of Tuple2 = 1014
Type of Tuple2 = System.Tuple`2[System.Int32,System.Int32]
การอ่าน Type Name ของ Tuple
รูปแบบ: System.Tuple`N[T1, T2, ..., TN]
`N= จำนวน generic type parameters (arity)T1, T2, ...= ชนิดข้อมูลของแต่ละ element- Nested tuple จะแสดงเป็น type argument ภายใน
ตัวอย่างการอ่าน
System.Tuple`2[System.Int32,System.Int32]= Tuple<int, int> (2 elements)System.Tuple`3[System.Int32,System.Int32,System.Tuple`2[System.Int32,System.Int32]]= Tuple<int, int, Tuple<int, int>> (3 elements, ตัวที่ 3 เป็น nested tuple)
Tuple แบบใหม่: ValueTuple (C# 7+)
ใน C# 7+ มี ValueTuple (struct) ที่มี syntax สะดวกกว่า:
// Tuple syntax (C# 7+)
var tuple = (10, 20, "hello");
Console.WriteLine(tuple.GetType()); // System.ValueTuple`3[Int32, Int32, String]
// Named elements
var person = (Name: "John", Age: 30);
Console.WriteLine(person.Name); // John
Console.WriteLine(person.GetType()); // System.ValueTuple`2[String, Int32]
ความแตกต่าง Tuple (class) vs ValueTuple (struct)
| คุณสมบัติ | Tuple (Class) | ValueTuple (Struct) |
|---|---|---|
| Type | Reference type | Value type |
| Mutability | Immutable | Mutable |
| Performance | Heap allocation | Stack allocation (usually) |
| Syntax | Tuple.Create() | (x, y, z) |
| Named elements | ไม่รองรับ | รองรับ |
| Equality | Value-based | Value-based |