昨天有朋友问我C#中索引器怎么用的,给他解释了一番。问问其他的人,也回答不会用。显然的,因为觉得索引器不常用,都把它淡忘了,其实索引器我们经常在使用:访问数组、集合元素时:array[i],访问DataGridView、GridView时:gridView.DataKeys[index][“cellName”],ADO.NET中:DataReader[“columnName”]。等等,用的还是比较多的,因此很有必要了解下这东东。
1. 什么是索引器
索引器允许类和结构的实例用下标进行访问,这种方式类似于访问数组、集合的元素,但不单单是通过下标,例如通过对象的各属性值也是可以的。索引器写在类或者结构中,其格式类似于:
public object this[int index] |
get { return objects[int]; } |
set { objects[int] = value; } |
索引器是特殊的属性,可以有get、set访问器,可以重载。object是返回的对象类型,this代表类或结构自己,int index表示索引类型。这与索引器的调用格式:对象[索引],相对应。下面我们通过例子来实践下:我们写个汽车类,为它添加索引器。
2. 为类添加索引器
首先创建Car类:
public string Brand { get; set; } |
public string Color { get; set; } |
/// 覆盖object的ToString()方法 |
public override string ToString() |
return string.Format("A {0} {1}.", this.Color, this.Brand); |
为汽车添加了品牌(Brand)与颜色(Color)属性,并覆盖了ToString()方法,用于显示汽车的信息。接着我们创建Cars类,在里面添加索引器访问Car:
public IList<Car> List { get; set; } |
/// <param name="index">下标</param> |
/// <returns>汽车</returns> |
public Car this[int index] |
get { return this.List[index]; } |
/// <param name="brand">品牌</param> |
/// <returns>汽车</returns> |
public Car this[string brand] |
for (int i = 0; i < List.Count; i++) |
// 为false的情况较多,所以这里用Equals比较, |
// 《C# 中“Equals”与“==”的速度比较》 |
if (brand.Equals(this.List[i].Brand)) |
Cars有个Car集合,写了两个索引器,分别用下标和汽车品牌进行访问,构成了重载,这里若不写下标索引器是不能用cars[index]访问Car的。下面我们编写入口,测试索引器是否起作用了,实例化3辆车:黑色宝马、红色奔驰、黄色保时捷。
public static void Main(string[] args) |
new Car { Brand = "BMW", Color = "Black" }, // 黑色宝马 |
new Car { Brand = "Benz", Color = "Red" }, // 红色奔驰 |
new Car { Brand = "Porsche", Color = "Yellow" } // 黄色保时捷 |
Console.WriteLine(cars[0].ToString()); |
Console.WriteLine(cars["Porsche"].ToString()); |
分别用下标和品牌进行了访问,下面是运行结果: