黑马程序员技术交流社区

标题: C#索引器 [打印本页]

作者: 闫炳颖    时间: 2011-12-4 19:49
标题: C#索引器
本帖最后由 闫炳颖 于 2011-12-5 21:21 编辑

C#种索引器实现过程,是否只能根据数字索引?
作者: 付炯    时间: 2011-12-4 22:56
本帖最后由 付炯 于 2011-12-4 22:56 编辑

没看明白你想问什么 C#的索引器的定义方法非常类似于属性 格式如下
  1. <modifiers> <type> this[<parameter list>]
  2. {
  3.     get
  4.     {
  5.         ...
  6.     }
  7.     set
  8.     {
  9.         ...
  10.     }
  11. }
复制代码

作者: 林洲    时间: 2011-12-4 23:42
本帖最后由 林洲 于 2011-12-4 23:48 编辑

这是从杨老师的基础视频里整理来的一个例子,希望对你有些帮助:
class Program  //在这里使用索引
    {
        static void Main(string[] args)
        {
            Person p1 = new Person();
            p1[1] = "小明";
            Console.WriteLine(p1[1]+p1[2]);
            Console.WriteLine( p1["tom", 3, 9]);//索引的重载,因为定义了两个不同参数的索引器
            Console.ReadKey();
        }
    }


class Person
    {
        private string firstName = "大毛";
        private string secondName = "二毛";
        public string this[int index] //this可以看做是索引器函数的类名,中括号中的index表示用户输入的序号,public string中的string是由get中的方法体来决定的,返回的是string,那么这里就是string,是其他的类型时,这里就是其它相应的数据类型即索引器返回的数据类型
        {
            get
            {
                if (index==1)
                {
                    return firstName;
                }
                else if (index==2)
                {
                    return secondName;
                }
                else
                {
                    throw new Exception("错误的序号!");
                }
            }
            set
            {
                if (index==1)
                {
                    firstName = value;
                }
                else if (index==2)
                {
                    secondName = value;
                }
                else
                {
                    throw new Exception("错误的序号!");
                }
            }
        }

        public string this[string name, int x, int y] //可以只有get(只读的)没有set;也可以只有set(只写),没有get
        {
            get { return name + x + y; }
        }
    }




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2