C#学习笔记<七> 索引器

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] value = { 3, 5, 6, 7 };
            int i = value[0];
            Person p1 = new Person();
            p1[1] = "xiaoming";
            Console.WriteLine(p1[1] + p1[2]);
            Console.ReadKey();
        }
    }

    class Person
    {
        private string FirstName = "Xianwei";
        private string LastName = "Sui";
        public string this[int index]
        {
            set 
            {
                if (index == 1)
                {
                    FirstName = value;
                }
                else if (index == 2)
                {
                    LastName = value;
                }
                else
                {
                    throw new Exception("REEOR");
                }
            }
            get
            {
                if (index == 1)
                {
                    return FirstName;
                }
                else if (index==2)
                {
                    return LastName;
                }
                else
                {
                    throw new Exception("ERROR");
                }
            }
        }
    }
}
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person();
            Console.WriteLine(p1["Tom",20]);
            Console.ReadKey();
        }
    }

    class Person
    {
        public string this[string name, int i]
        {
            get { return name + i; }
        }
    }
}

你可能感兴趣的:(C#学习笔记<七> 索引器)