介绍
索引器使你可从语法上方便地创建类、结构或接口,以便客户端应用程序能像访问数组一样访问它们。 在主要目标是封装内部集合或数组的类型中,常常要实现索引器。例如,假设有一个类 TempRecord,它表示 24 小时的周期内在 10 个不同时间点所记录的温度(单位为华氏度)。 此类包含类型 float[] 的一个数组 temps,用于存储温度值。 通过在此类中实现索引器,客户端可采用 float temp = tr[4] 的形式(而非 float temp = tr.temps[4])访问 TempRecord 实例中的温度。 索引器表示法不但简化了客户端应用程序的语法;它还使类及其目标更容易直观地为其它开发者所理解。
若要在类或结构上声明索引器,请使用 this 关键字,如以下示例所示:
#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Iterator
{
class ConcreteAggregate : Aggregate
{
private IList<object> items = new List<object>();
public override Iteraotr CreateIterator()
{
return new ConcreteIterator(this);
}
public int Count
{
get { return items.Count; }
}
public object this[int index]
{
get { return items[index]; }
set { items.Insert(index, value); }
}
}
}