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

Indexer ใน C# คืออะไร

Indexer ใน C#

Indexer ช่วยให้อ็อบเจกต์สามารถเข้าถึงได้ด้วยดัชนี (Index) เหมือนอาร์เรย์ โดยใช้คีย์เวิร์ด this ร่วมกับพารามิเตอร์ดัชนี

ไวยากรณ์ (Syntax)

element-type this[int index]
{
    // The get accessor
    get
    {
        // คืนค่าตามดัชนีที่ระบุ
    }
    // The set accessor
    set
    {
        // ตั้งค่าตามดัชนีที่ระบุ
    }
}

ตัวอย่างการใช้งาน

using System;

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

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

        // Indexer declaration
        public string this[int index]
        {
            get
            {
                string tmp;
                if (index >= 0 && index <= size - 1)
                    tmp = namelist[index];
                else
                    tmp = "";
                return tmp;
            }
            set
            {
                if (index >= 0 && index <= size - 1)
                    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();
        }
    }
}

ผลลัพธ์

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

ประโยชน์ของ Indexer

  • ทำให้การเข้าถึงข้อมูลภายในอ็อบเจกต์เป็นธรรมชาติเหมือนอาร์เรย์
  • สามารถเพิ่มตรรกะตรวจสอบขอบเขต (Bounds checking) ได้ใน accessor
  • รองรับหลายพารามิเตอร์ (Multi-dimensional indexer)