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

คลาส Tuple ใน C#

หากต้องการคืนค่ามากกว่าหนึ่งค่าจากเมธอดของคลาส ให้ใช้ C# Tuples คลาสนี้มีเมธอด Static สำหรับสร้าง Tuple ได้ง่ายขึ้น Tuple ถูกนำเข้ามาใน .NET 4.0

ตัวอย่าง: ใช้ Tuple คืนค่าสองค่า

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Tuple<int, string> tuple = new Tuple<int, string>(2, "Tom");
        
        if (tuple.Item1 == 150)
        {
            Console.WriteLine(tuple.Item1);
        }
        if (tuple.Item2 == "Tom")
        {
            Console.WriteLine(tuple.Item2);
        }
    }
}

ผลลัพธ์

Tom

ข้อมูลเพิ่มเติม: คลาส Tuple (Static Class) มีเมธอด Create() หลาย overload สำหรับสร้าง Tuple 1-8 ค่าได้ง่ายขึ้น เช่น Tuple.Create(1, "two", 3.0) โดยไม่ต้องระบุ Generic Type Parameter ทุกครั้ง