8.7.7 Indexers

An indexer is a member that enables an object to be indexed in the same way
as an array. Whereas
properties enable field-like access, indexers enable array-like access.
As an example, consider the Stack class presented earlier. The designer of
this class might want to expose
array-like access so that it is possible to inspect or alter the items on
the stack without performing
unnecessary Push and Pop operations. That is, class Stack is implemented as
a linked list, but it also
provides the convenience of array access.
Indexer declarations are similar to property declarations, with the main
differences being that indexers are
nameless (the .name. used in the declaration is this, since this is being
indexed) and that indexers
include indexing parameters. The indexing parameters are provided between
square brackets. The example
using System;
public class Stack
{
private Node GetNode(int index) {
Node temp = first;
while (index > 0) {
temp = temp.Next;
index--;
}
return temp;
}
public object this[int index] {
get {
if (!ValidIndex(index))
throw new Exception("Index out of range.");
else
return GetNode(index).Value;
}
set {
if (!ValidIndex(index))
throw new Exception("Index out of range.");
else
GetNode(index).Value = value;
}
}
.
}
Chapter 8 Language Overview
39
class Test
{
static void Main() {
Stack s = new Stack();
s.Push(1);
s.Push(2);
s.Push(3);
s[0] = 33; // Changes the top item from 3 to 33
s[1] = 22; // Changes the middle item from 2 to 22
s[2] = 11; // Changes the bottom item from 1 to 11
}
}
shows an indexer for the Stack class.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值