8.7.7 Indexers

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航