索引器

using System;


namespace ClassStudy.Zheng 
{
    class My
    {
        private string name;// 索引值为0
        private string household;// 索引值为1

        /**
         * 索引器
         */
        public string this[int index]
        {
            set
            {
                if(index == 0)
                {
                    this.name = value;
                }
                else if (index == 1)
                {
                    this.household = value;
                }
                else
                {
                    Console.WriteLine("索引值有误");
                }   
            }
            get
            {
                if (index == 0)
                {
                    return this.name;
                }
                else if (index == 1)
                {
                    return this.household;
                }
                else
                {
                    return "索引值有误";
                }
            }
        }

        public static void Main(string[] args)
        {
            My my = new My();
            my[0] = "zbt";
            my[1] = "广州";

            Console.WriteLine("名字是{0},户口是{1}", my[0], my[1]);

            Console.ReadKey();
        }
    }
}


你可能感兴趣的:(C#面向对象基础,string,class)