索引器的使用

来源:互联网 发布:v2ex源码搭建 编辑:程序博客网 时间:2024/06/07 04:08
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace 索引器
{
    class Program
    {
        static void Main(string[] args)
        {
            MyIndexer myindexer1 = new MyIndexer();
            myindexer1[2] = 22;
            myindexer1[4] = 44;
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("myindexer1[{0}]={1}", i, myindexer1[i]);
            }
        }
    }
    class MyIndexer
    {
        private int[] arr = new int[5]{0,1,2,3,4};
        public int this[int index]
        {
            get
            {
                if (index >= 0 && index < 5) return arr[index];
                else return 0;
            }
            set
            {
                if (index >= 0 && index < 5)
                    arr[index] = value;
            }

         }
        public int Length
        {
            get { return arr.Length; }
        }


      }
}
0 0