索引器
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。它可以使得像数组那样对对象使用下标。它提供了通过索引方式方便地访问类的数据信息的方法。
个人理解:索引器是属性的增强。他提供一种索引方式,像下标或是字符串,使我们实现对数据的快速查找。
实例:
class Program
{
static void Main(string[] args)
{
Album friends = new Album();
Photo first = new Photo("Jean");
Photo second = new Photo("Smith");
friends[0] = first;
friends[1] = second;
//用下标索引
Photo obj1Photo = friends[1];
Console.WriteLine(obj1Photo.Title);
//用字符串索引
Photo obj2Photo = friends["Smith"];
Console.WriteLine(obj2Photo.Title);
}
}
public class Photo
{
private String _title;
public string Title
{
get { return _title; }
}
public Photo()
{
}
public Photo(string title)
{
_title = title;
}
}
public class Album : Photo
{
Photo[] photos;
public Album()
{
photos = new Photo[2];
}
public Album(int capacity)
{
photos = new Photo[capacity];
}
public Photo this[int index]
{
get
{
if (index < 0 || index > photos.Length)
{
Console.WriteLine("索引无效");
return null;
}
return photos[index];
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return;
}
photos[index] = value;
}
}
public Photo this[string title]
{
get
{
foreach (Photo p in photos)
{
if (p.Title == title)
return p;
}
Console.WriteLine("未找到");
return null;
}
}
}