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

Indexer (Chỉ mục) trong C# - Cú pháp và ví dụ

Indexer cho phép một đối tượng được truy cập bằng chỉ số (index) giống như mảng (obj[index]). Đây là cách tự nhiên để expose dữ liệu nội bộ dưới dạng tập hợp.

Cú pháp

public KieuTraVe this[int index]
{
    get { // trả về giá trị tại index }
    set { // gán giá trị tại index }
}

Ví dụ hoàn chỉnh

using System;

namespace Demo
{
    class Program
    {
        private string[] namelist;
        public static int Size = 10;

        public Program()
        {
            namelist = new string[Size];
            for (int i = 0; i < Size; i++)
                namelist[i] = "N. A.";
        }

        // Indexer
        public string this[int index]
        {
            get
            {
                if (index >= 0 && index < Size)
                    return namelist[index];
                return ""; // hoặc throw IndexOutOfRangeException
            }
            set
            {
                if (index >= 0 && index < Size)
                    namelist[index] = value;
            }
        }

        static void Main(string[] args)
        {
            Program names = new Program();
            names[0] = "Tom";
            names[1] = "Jacob";
            names[2] = "Jack";
            names[3] = "Amy";
            names[4] = "Katy";
            names[5] = "Taylor";
            names[6] = "Brad";
            names[7] = "Scarlett";
            names[8] = "James";

            for (int i = 0; i < Program.Size; i++)
                Console.WriteLine(names[i]);
            
            Console.ReadKey();
        }
    }
}

Kết quả

Tom
Jacob
Jack
Amy
Katy
Taylor
Brad
Scarlett
James
N. A.

Đặc điểm quan trọng

  • Indexer dùng từ khóa this thay vì tên phương thức.
  • Có thể nạp chồng (overload) indexer với nhiều kiểu tham số khác nhau (ví dụ: this[string key], this[int x, int y]).
  • Thường dùng trong các lớp collection tùy chỉnh, wrapper mảng, hoặc truy cập dữ liệu theo kiểu dictionary.
  • Có thể chỉ đọc (chỉ có get) hoặc chỉ ghi (chỉ có set).

Lưu ý: Code gốc có lỗi khai báo size trước khi dùng. Đã sửa: Size là static const, namelist khởi tạo trong constructor.