Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 107: Indexer

Section 107.1: A simple indexer

class Foo

{

private string[] cities = new[] { "Paris", "London", "Berlin" };

public string this[int index]

{

get {

return cities[index];

}

set {

cities[index] = value;

}

}

}

Usage:

var foo = new Foo();

//access a value string berlin = foo[2];

//assign a value

foo[0] = "Rome";

View Demo

Section 107.2: Overloading the indexer to create a SparseArray

By overloading the indexer you can create a class that looks and feels like an array but isn't. It will have O(1) get and set methods, can access an element at index 100, and yet still have the size of the elements inside of it. The SparseArray class

class SparseArray

{

Dictionary<int, string> array = new Dictionary<int, string>();

public string this[int i]

{

get

{

if(!array.ContainsKey(i))

{

return null;

}

return array[i];

}

set

{

if(!array.ContainsKey(i)) array.Add(i, value);

}

GoalKicker.com – C# Notes for Professionals

558

}

}

Section 107.3: Indexer with 2 arguments and interface

interface ITable {

// an indexer can be declared in an interface object this[int x, int y] { get; set; }

}

class DataTable : ITable

{

private object[,] cells = new object[10, 10];

///<summary>

///implementation of the indexer declared in the interface

///</summary>

///<param name="x">X-Index</param>

///<param name="y">Y-Index</param>

///<returns>Content of this cell</returns>

public object this[int x, int y]

{

get

{

return cells[x, y];

}

set

{

cells[x, y] = value;

}

}

}

GoalKicker.com – C# Notes for Professionals

559