Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Trả về nhiều giá trị từ phương thức trong C#

Tuple có thể dùng để trả về nhiều giá trị từ phương thức trong C#. Nó cho phép lưu trữ data set chứa nhiều giá trị có thể liên quan hoặc không liên quan. Tuple mới gọi là ValueTuple từ C# 7.0 (.NET Framework 4.7).

ValueTuples vừa performant vừa tham chiếu được bằng tên do lập trình viên chọn. ValueTuple cung cấp cơ chế nhẹ để trả về nhiều giá trị từ phương thức hiện có. ValueTuples có sẵn dưới gói NuGet System.ValueTuple.

public (int, string, string) GetPerson() { }

Ví dụ 1

using System;

namespace DemoApplication
{
    class Program
    {
        public static void Main()
        {
            var fruits = GetFruits();
            Console.WriteLine($"Fruit Id: {fruits.Item1}, Name: {fruits.Item2}, Size: {fruits.Item3}");
            Console.ReadLine();
        }

        static (int, string, string) GetFruits()
        {
            return (Id: 1, FruitName: "Apple", Size: "Big");
        }
    }
}

Kết quả

Fruit Id: 1, Name: Apple, Size: Big

Trong ví dụ, GetFruits() trả về nhiều giá trị (int, string, string). Giá trị tuple truy cập qua fruits.Item1, Item2, Item3.

Có thể lấy từng member bằng deconstructing:

(int FruitId, string FruitName, string FruitSize) = GetFruits();

Ví dụ 2

using System;

namespace DemoApplication
{
    class Program
    {
        public static void Main()
        {
            (int FruitId, string FruitName, string FruitSize) = GetFruits();
            Console.WriteLine($"Fruit Id: {FruitId}, Name: {FruitName}, Size: {FruitSize}");
            Console.ReadLine();
        }

        static (int, string, string) GetFruits()
        {
            return (Id: 1, FruitName: "Apple", Size: "Big");
        }
    }
}

Kết quả

Fruit Id: 1, Name: Apple, Size: Big