DevelopersGuide2Moving2MicrosoftNET 86c09926 affc 4e14 bec0/119 - 119

Kapitola 9: C++ → C#: Co potřebujete vědět pro přechod z C++ k C#

INDEXER
V C# lze vytvářet sady objektů, s nimiž můžete pracovat jako s poli. Představte si, že byste chtěli vytvořit seznam, jenž by byl naplněn textovými řetězci, které by byly posléze zobrazovány. Bylo by hezké, kdybychom mohli k jednotlivým položkám seznamu přistupovat pomocí indexu jako při práci s poli.
string theFirstString = myListBox[0]; string theLastString = myListBox[Length-1];

Tento styl práce nám umožňuje programová konstrukce, které se říká indexer. Indexer se podobá na vlastnost, ale podporuje syntaxi operátoru index.

Operátor index
public string this[int index] { get { if (index < 0 || index >= myStrings.Length) { // handle bad index } return myStrings[index]; } set { myStrings[index] = value; } }

Programový kód ve třídě ListBox ukazuje, jak implementovat velice jednoduchou třídu ListBox s podporou indexování.

Třída ListBox
using System; // a simplified ListBox control public class ListBoxTest { // initialize the list box with strings public ListBoxTest(params string[] initialStrings) { // allocate space for the strings myStrings = new String[256]; // copy the strings passed in to the constructor foreach (string s in initialStrings) { myStrings[myCtr++] = s; } } // add a single string to the end of the list box public void Add(string theString) { myStrings[myCtr++] = theString; }

118

Přecházíme na platformu Microsoft .NET

Ještě nehodnoceno. Buďte první :-)

(c)2011 Edgehunt Corporation
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .