索引器:索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
语法:[访问修饰符] 数据类型 this [数据类型 标识符]
{
get{};
set{};
}
下面是视频中的一个实例,描述的是通过索引,名称对照片进行检索。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication11 { class Program { static void Main(string[] args) { Ablum MyAblum1=new Ablum (2); //创建容量为2的相册 //创建2张照片 Photo first=new Photo ("小楚"); Photo second=new Photo ("小王"); //向相册加载照片 MyAblum1 [0]=first ; MyAblum1 [1]=second; //按索引检索 Photo testPhots=MyAblum1 [0]; Console .WriteLine (testPhots.Title ); //按名称检索 Photo testPhotos=MyAblum1 ["小王"]; Console .WriteLine (testPhotos .Title ); } } class Photo { private string PhotoTitle; //声明私有变量 //建立默认值的构造函数 public Photo() { PhotoTitle ="楚广明"; } public Photo (string title) //含有一个参数的构造函数 { PhotoTitle =title ; } public string Title //指定返回值 { get {return PhotoTitle ;} } } class Ablum { Photo [] photos; //定义数组 public Ablum () { photos =new Photo[3]; //定义数组默认元素个数 } public Ablum (int Capacity) //数组的元素任意个数 { photos =new Photo [Capacity ]; } public Photo this[int index] //带有int参数的Photo索引器 { get { //访问 if (index <0||index >=photos .Length ) //验证索引范围 { Console .WriteLine ("索引有问题"); return null ; //使用null指示失败 } return photos [index ]; //对于有效索引,返回请求的照片 } set { if (index <0||index >=photos .Length ) { Console.WriteLine("索引有问题"); return; } photos [index ]=value ; } } public Photo this[string title] //带有string参数的Photo索引器 { get { foreach (Photo p in photos ) //遍历数组中的所有照片 { if (p.Title ==title ) //将照片中的标题与索引器参数进行比较 return p; } Console.WriteLine ("找不到"); return null ; } } } }
原文:http://blog.csdn.net/lxy344x/article/details/21556199