C#索引器关键实例代码
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Photo firstPhoto = new Photo("小轮");
Photo secondPhoto = new Photo("小气");
Ablum obj = new Ablum(2);
obj[0] = firstPhoto;
obj[1] = secondPhoto;
Console.WriteLine(obj["小轮"].Title);
Console.WriteLine(obj[1].Title);
}
}
/// <summary>
/// 照片类
/// 字段title 照片标题,测试用
/// </summary>
class Photo
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
public Photo()
{
this.Title = "默认名称";
}
public Photo(string title)
{
this.Title = title;
}
}
class Ablum
{
public Photo[] photos;
public Ablum()
{
photos = new Photo[2];
}
public Ablum(int length)
{
photos = new Photo[length];
}
/// <summary>
/// 使用int类型的索引器
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Photo this[int index]
{
get
{
if (index < 0 || index > photos.Length - 1)
{
Console.Write("索引值无效");
return null;
}
return photos[index];
}
set
{
if (index < 0 || index > photos.Length - 1)
{
Console.Write("索引值无效");
return;
}
photos[index] = value;
}
}
/// <summary>
/// 使用string类型的索引器
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Photo this[string indexStr]
{
get
{
foreach (Photo objPhoto in photos)
{
if (objPhoto.Title.Equals(indexStr))
return objPhoto;
}
Console.WriteLine("索引值错误");
return null;
}
set
{
int count = 0;
foreach (Photo objPhoto in photos)
{
if (objPhoto.Title.Equals(indexStr))
{
photos[count] = value;
}
count++;
return;
}
}
}
}
}
输出结果:小轮
小气