每天学一点,每天积累一点,进步就不止一点点!PS:好记性不如烂笔头,学会总结,学会思考~~~ ----要飞翔,必须靠自己!

灰太狼的梦想

好记性不如烂笔头,学会总结,学会思考~~~

C#--索引

  • 索引是一组get和set访问器,类似于属性的访问器。
  • 索引和属性在很多方面是相似的。
  • 和属性一样,索引不用分配内存来存储;
  • 索引和属性都主要被用来访问其他数据成员,这些成员和他们关联,他们为这些成员提供设置和获取访问;
  • 属性通常表示单独的数据成员;
  • 索引通常表示多个数据成员;
  • 可以把索引想象成提供获取和设置类的多个数据成员的属性,通过提供索引在许多可能的数据成员中进行选择。索引本身可以是任何类型的,不仅仅是数值类型;

使用索引时,另外还有一些注意事项如下:

  • 和属性一样,索引可以只有一个访问器,也可以两个都有;
  • 索引总是实例成员。因此索引不能被声明为static;
  • 和属性一样,实现get和set访问器的代码,不一定要关联到某个字段或者属性。这段代码可以做任何事情也可以什么都不做,只要get访问器返回某个指定类型即可。

声明索引:

声明索引的语法如此下,请注意以下几点:

  • 索引没有名称,在名称位置的是关键字this;
  • 参数列表,在方括号中间;
  • 参数列表中至少必须声明一个参数。

声明索引类似于声明属性。下图有他们的相同点和不同点:

 

索引的set访问器:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
   public class Employee
    {
       public string FirstName;
       public string Lastname;
       public string CityOfBirth;

       /// <summary>
       /// 创建索引
       /// </summary>
       /// <param name="index"></param>
       /// <returns></returns>
       public string this[int index]
       {
           set 
           {
               switch (index)
               {
                   case 0: FirstName = value; break;
                   case 1: Lastname = value; break;
                   case 2: CityOfBirth = value; break;
                   default:
                       throw new ArgumentOutOfRangeException("index");
               }
           }
           get 
           
           {
               switch (index)
               {
                   case 0: return FirstName;
                   case 1: return Lastname;
                   case 2: return CityOfBirth;
                   default:
                       throw new ArgumentOutOfRangeException("index");
               }
           }
       }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 索引复习
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student() 
            {
            firstName="c",
            lastName="b",
            cityOfBirth="w"
            
            };
            //测试索引的访问
            Console.WriteLine("firstName={0}",stu[0]);
            Console.ReadKey();
            
        }
    }
}

 

posted @ 2015-10-05 18:00  灰太狼的梦想  阅读(2471)  评论(2编辑  收藏  举报