phoebird 发表于 2013-2-4 20:35:17

C# 使用索引器

using System;using System.Collections.Generic;using System.Text;//使用索引器namespace interfaceDemo{    public class Photo//相片类    {      string title;      public Photo(string title)//构造方法      {            this.title = title;                     }      public string Title//声明一个只读属性      {            get            {                return this.title;            }      }    }    class Album//相册类    {      Photo[] photos;//通过此数组存放相片      public Album(int num)//初始化相册容量      {            photos = new Photo;      }      public Photo this//定义一个可读写的索引器,可实现按序号读写       {         get         {               return this.photos;         }         set         {               this.photos = value;         }         }      public Photo this//重载一个只读索引器,按标题查找      {            get             {                for (int i = 0; i < photos.Length; i++)                {                  if (photos.Title == title)//判断标题是否相同                  {                        return photos;                  }                }                Console.WriteLine("没有找到");                return null;            }      }      }    class TestIndexDemo    {      static void Main(string[] args)      {            Photo first = new Photo("first");            Photo second = new Photo("second");            Album ab = new Album(20);            ab = first;//使用第一个索引器将照片存入相册中            ab = second;            Photo obj = ab;//使用第一个索引器根据序号读取相册中的照片            Console.WriteLine(obj.Title);            obj = ab["first"];//使用第二个索引器根据标题取出照片            Console.WriteLine(obj.Title);            Console.ReadLine();      }    }} 
页: [1]
查看完整版本: C# 使用索引器