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

Indexer nạp chồng (Overloaded Indexers) trong C#

Indexer cho phép object được index như mảng. Khi định nghĩa indexer cho class, class hành xử như mảng ảo. Truy cập instance bằng [].

Indexer có thể nạp chồng (overloaded). Khai báo nhiều tham số, mỗi tham số kiểu khác nhau.

Ví dụ

using System;

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

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

        // Indexer 1: tham số int
        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;
            }
        }

        // Indexer 2: tham số string
        public int this[string name] {
            get {
                int index = 0;
                while (index < size) {
                    if (namelist[index] == name) return index;
                    index++;
                }
                return index;
            }
        }

        static void Main(string[] args) {
            IndexedNames names = new IndexedNames();
            names[0] = "John"; names[1] = "Joe"; names[2] = "Graham";
            names[3] = "William"; names[4] = "Jack"; names[5] = "Tom"; names[6] = "Tim";
            // dùng indexer int
            for (int i = 0; i < IndexedNames.size; i++) Console.WriteLine(names[i]);
            // dùng indexer string
            Console.WriteLine(names["Nuha"]);
            Console.ReadKey();
        }
    }
}

Kết quả

John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10