现在的位置: 首页 > 综合 > 正文

C#学习笔记七索引器

2013年01月07日 ⁄ 综合 ⁄ 共 1071字 ⁄ 字号 评论关闭

索引器

 

namespace 索引器

{

    class Program

    {

        static void Main(string[] args)

        {

            Person p1 = new Person();

            p1[1] = "小明";

            Console.WriteLine(p1[1] + p1[2]);

            Console.ReadKey();

        }

    }

    public class Person

    {

        private string firstName = "大毛";

        private string secondName = "二毛";

 

        //下面这个就是索引器

        public string this[int index]//索引可以有不止一个参数,setget可以只有一个

        {

            set

            {

                if (index == 1)

                {

                    firstName = value;

                }

                else if (index == 2)

                {

                    secondName = value;

                }

                else

                {

                    throw new Exception("输入的值不合适");

                }

            }

            get

            {

                if (index == 1)

                {

                    return firstName;

                }

                else if (index == 2)

                {

                    return secondName;

                }

                else

                {

                    throw new Exception("输入的值不合适");

                }

            }

        }

    }

}

抱歉!评论已关闭.