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

Tạo ValueTuple có tên (Named ValueTuple) trong C# 7+

Từ C# 7.0, ValueTuple hỗ trợ named elements (phần tử có tên), cho phép truy cập bằng tên thay vì Item1, Item2. Code dễ đọc, tự tài liệu hóa.

Cài đặt (chỉ .NET Framework cũ)

  1. Right-click project → Manage NuGet Packages
  2. Browse → "System.ValueTuple" → Install

.NET Core / .NET 5+ đã tích hợp sẵn.

Ví dụ: ValueTuple có tên

var myTuple = (marks: 95, name: "jack", subject: "maths");

// Truy cập bằng tên
Console.WriteLine(myTuple.marks);    // 95
Console.WriteLine(myTuple.name);     // jack
Console.WriteLine(myTuple.subject);  // maths

// Cũng vẫn truy cập được bằng Item1, Item2...
Console.WriteLine(myTuple.Item1);    // 95

Mã nguồn hoàn chỉnh

using System;

class Program
{
    static void Main()
    {
        var myTuple = (marks: 95, name: "jack", subject: "maths");
        // Add System.ValueTuple package to run this program
        
        Console.WriteLine("Student Marks: " + myTuple.marks);
        Console.WriteLine("Student Name: " + myTuple.name);
        Console.WriteLine("Student Subject: " + myTuple.subject);
    }
}

Kết quả

Student Marks: 95
Student Name: Jack
Student Subject: Maths

Các cách khai báo ValueTuple

Cú phápVí dụTruy cập
Positional(1, 2, 3).Item1, .Item2
Named(x: 1, y: 2).x, .y (và Item1, Item2)
Mixed(1, y: 2, 3).Item1, .y, .Item3
Từ biếnvar x=1; var t = (x, y:2)Tên biến tự thành tên element

Deconstruction (Phân rã)

var (marks, name, subject) = myTuple;
// Hoặc bỏ qua
var (_, name, _) = myTuple;

Lưu ý

  • Tên element được lưu ở metadata (compile-time), không ảnh hưởng runtime.
  • ValueTuple là struct (value type) - hiệu suất tốt, mutable.
  • So sánh bằng giá trị (value equality) tự động.