Студопедия
Новини освіти і науки:
МАРК РЕГНЕРУС ДОСЛІДЖЕННЯ: Наскільки відрізняються діти, які виросли в одностатевих союзах


РЕЗОЛЮЦІЯ: Громадського обговорення навчальної програми статевого виховання


ЧОМУ ФОНД ОЛЕНИ ПІНЧУК І МОЗ УКРАЇНИ ПРОПАГУЮТЬ "СЕКСУАЛЬНІ УРОКИ"


ЕКЗИСТЕНЦІЙНО-ПСИХОЛОГІЧНІ ОСНОВИ ПОРУШЕННЯ СТАТЕВОЇ ІДЕНТИЧНОСТІ ПІДЛІТКІВ


Батьківський, громадянський рух в Україні закликає МОН зупинити тотальну сексуалізацію дітей і підлітків


Відкрите звернення Міністру освіти й науки України - Гриневич Лілії Михайлівні


Представництво українського жіноцтва в ООН: низький рівень культури спілкування в соціальних мережах


Гендерна антидискримінаційна експертиза може зробити нас моральними рабами


ЛІВИЙ МАРКСИЗМ У НОВИХ ПІДРУЧНИКАХ ДЛЯ ШКОЛЯРІВ


ВІДКРИТА ЗАЯВА на підтримку позиції Ганни Турчинової та права кожної людини на свободу думки, світогляду та вираження поглядів



Контакти
 


Тлумачний словник
Авто
Автоматизація
Архітектура
Астрономія
Аудит
Біологія
Будівництво
Бухгалтерія
Винахідництво
Виробництво
Військова справа
Генетика
Географія
Геологія
Господарство
Держава
Дім
Екологія
Економетрика
Економіка
Електроніка
Журналістика та ЗМІ
Зв'язок
Іноземні мови
Інформатика
Історія
Комп'ютери
Креслення
Кулінарія
Культура
Лексикологія
Література
Логіка
Маркетинг
Математика
Машинобудування
Медицина
Менеджмент
Метали і Зварювання
Механіка
Мистецтво
Музика
Населення
Освіта
Охорона безпеки життя
Охорона Праці
Педагогіка
Політика
Право
Програмування
Промисловість
Психологія
Радіо
Регилия
Соціологія
Спорт
Стандартизація
Технології
Торгівля
Туризм
Фізика
Фізіологія
Філософія
Фінанси
Хімія
Юриспунденкция






Topic: Indexers

 

An indexerallows an object to be indexed like an array. When you define an indexer for a class, this class behaves like a virtual array. You can then access the instance of this class using the array access operator ([ ]).

Syntax

A one dimensional indexer has the following syntax:

 

element-type this[int index]

{

// The get accessor.

get

{

// return the value specified by index

}

// The set accessor.

set

{

// set the value specified by index

}

}

 

Use of Indexers

Declaration of behavior of an indexer is to some extent similar to a property. Like properties, you use getand setaccessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not defined with names, but with the thiskeyword, which refers to the object instance. The following example demonstrates the concept:

 

using System;

namespace IndexerApplication

{

class IndexedNames

{

private string[] namelist = new string[size];

static public int size = 10;

public IndexedNames()

{

for (int i = 0; i < size; i++)

namelist[i] = "N. A.";

}

public string this[int index]

{

get

{

string tmp;

if( index >= 0 && index <= size-1 )

{

tmp = namelist[index];

}

else

{

tmp = "";

}

return ( tmp );

}

 

set

{

if( index >= 0 && index <= size-1 )

{

namelist[index] = value;

}

}

}

static void Main(string[] args)

{

IndexedNames names = new IndexedNames();

names[0] = "Zara";

names[1] = "Riz";

names[2] = "Nuha";

names[3] = "Asif";

names[4] = "Davinder";

names[5] = "Sunil";

names[6] = "Rubic";

for ( int i = 0; i < IndexedNames.size; i++ )

{

Console.WriteLine(names[i]);

}

Console.ReadKey();

}

}

}

 

When the above code is compiled and executed, it produces the following result:

Zara

Riz

Nuha

Asif

Davinder

Sunil

Rubic

N. A.

N. A.

N. A.

 

Overloaded Indexers

Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string.

The following example demonstrates overloaded indexers:

using System;

namespace IndexerApplication

{

class IndexedNames

{

private string[] namelist = new string[size];

static public int size = 10;

public IndexedNames()

{

for (int i = 0; i < size; i++)

{

namelist[i] = "N. A.";

}

}

public string this[int index]

{

get

{

string tmp;

if( index >= 0 && index <= size-1 )

{

tmp = namelist[index];

}

else

{

tmp = "";

}

return ( tmp );

}

set

{

if( index >= 0 && index <= size-1 )

{

namelist[index] = value;

}

}

}

public int this[string name]

{

get

{

int index = 0;

while(index < size)

{

if (namelist[index] == name)

{

return index;

 

}

index++;

}

return index;

}

}

static void Main(string[] args)

{

IndexedNames names = new IndexedNames();

names[0] = "Zara";

names[1] = "Riz";

names[2] = "Nuha";

names[3] = "Asif";

names[4] = "Davinder";

names[5] = "Sunil";

names[6] = "Rubic";

//using the first indexer with int parameter

for (int i = 0; i < IndexedNames.size; i++)

{

Console.WriteLine(names[i]);

}

//using the second indexer with the string parameter

Console.WriteLine(names["Nuha"]);

Console.ReadKey();

}

}

}

 

When the above code is compiled and executed, it produces the following result:

Zara

Riz

Nuha

Asif

Davinder

Sunil

Rubic

N. A.

N. A.

N. A.

 

 

Another example:

Output:

 




Переглядів: 175

Не знайшли потрібну інформацію? Скористайтесь пошуком google:

 

© studopedia.com.ua При використанні або копіюванні матеріалів пряме посилання на сайт обов'язкове.


Генерація сторінки за: 0.008 сек.