Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

C# Tuple: การเข้าถึงองค์ประกอบ (Access Tuple Elements)

การเข้าถึงค่าใน Tuple ขึ้นอยู่กับประเภท Tuple ที่ใช้: ValueTuple (C# 7+) หรือ Tuple Class (Legacy)

ValueTuple (Modern - แนะนำ)

// Named Elements (Best Practice)
var person = (Id: 1, Name: "Amit", Age: 25, City: "Bangkok");

// เข้าถึงด้วยชื่อ (Named)
Console.WriteLine(person.Name);  // "Amit"
Console.WriteLine(person.Age);   // 25

// เข้าถึงด้วย Index (Item1, Item2...) - ไม่แนะนำถ้ามีชื่อ
Console.WriteLine(person.Item2); // "Amit"

// Deconstruction
var (id, name, age, city) = person;

Tuple Class (Legacy)

using System;

public class Program
{
    public static void Main()
    {
        var myTuple = Tuple.Create(1, 2.5M, "Amit", "100");
        
        // เข้าถึงผ่าน Item Properties เท่านั้น
        Console.WriteLine("Item1: " + myTuple.Item1); // 1
        Console.WriteLine("Item2: " + myTuple.Item2); // 2.5
        Console.WriteLine("Item3: " + myTuple.Item3); // Amit
        Console.WriteLine("Item4: " + myTuple.Item4); // 100
    }
}

ผลลัพธ์

Item1: 1
Item2: 2.5
Item3: Amit
Item4: 100

Comparison Table

FeatureValueTupleTuple Class
Access by Name✓ (Named Tuples)✗
Access by IndexItem1, Item2...Item1, Item2...
Deconstruction✓ var (a,b) = t;✗
MutabilityMutableImmutable
PerformanceStruct (Stack)Class (Heap)

Best Practice

  • ใช้ ValueTuple with Named Elements สำหรับโค้ดใหม่
  • Return Multiple Values จาก Method: public (int Sum, int Count) Calculate(int[] arr)
  • Discard ไม่ต้องการ: var (sum, _) = Calculate(arr);
  • หลีกเลี่ยง Tuple Class ยกเว้น Legacy Code / Interop