首页 > 代码库 > C#之索引器

C#之索引器

实际中不使用这个东西,只做了解

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 索引器 {
    class Program {
        static void Main(string[] args) {
            person p = new person();
            p[0] = 1;
            p[1] = 2;
            p[2] = 3;
            p[3] = 4;
            p[4] = 5;
            foreach(var item in p.Numbers) {
                Console.WriteLine(item);
            }
            p["0"] = "1";
            p["1"] = "2";
            p["2"] = "3";
            p["3"] = "4";
            p["4"] = "5";
            Console.WriteLine(p["0"]);
            Console.ReadLine();
        }
    }
    class person {
       
        private int[] _numbers = new int[5];
        public int[] Numbers {
            get { return _numbers; }
            set { _numbers = value; }
        }
        //索引器,让对象以索引的方式操作数组
        public int this[int index] {
            get { return _numbers[index]; }
            set { _numbers[index] = value; }
        }

        Dictionary<string, string> dic = new Dictionary<string, string>();
        public string this[string index] {
            set { dic[index] = value; }
            get { return dic[index]; }
        }
    }
}

 

C#之索引器