Indexer

using System;

namespace Indexer
{
    class Demo
    {
        private string[] names = new string[size];
        static  public  int size = 10;
        public Demo()
        {
            for(int i = 0; i < size; i++)
            {
                names[i] = "LT." + i;
            }
        }
        public string this[int index]
        {
            get { 
                string tmp; 
                if(index>=0 && index < size - 1)
                {
                    tmp = names[index];
                }
                else
                {
                    tmp = "";
                }
                return tmp;
            }

            set
            {
                if(index>=0 && index < size - 1)
                {
                    names[index] = value;
                }
            }
        }
        public int this[string str]
        {
            get
            {
                int i = 0;
                bool f = false;
                while (i < size)
                {
                    if (names[i] == str) f = true; break;                   
                    i++;                 
                }
                return f ? i : -1;

            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();
            demo[0] = "uzi";
            demo[1] = "xiaohu";
            demo[2] = "ming";
            demo[3] = "mlxg";
            demo[4] = "letme";

            for(int i = 0; i < Demo.size; i++)
            {
                Console.WriteLine(demo[i]);
            }

            Console.WriteLine(demo["letmejj"]);
        }
    }
}

你可能感兴趣的:(C#)