Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Руководство_по_C++_CLI.doc
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
8.1 Mб
Скачать

36.6.5Получение индекса элемента

Метод Contains() используется для проверки того, содержится ли заданный элемент в коллекции. Если известно, что элемент в коллекции есть, метод IndexOf интерфейса IList позволяет получить его индекс:

int IndexOf(Object^ value);

Если элемент со значением value найден в коллекции, метод возвращает его индекс, а в противном случае он возвращает -1. Пример реализации этого метода:

using namespace System;

using namespace System::Collections;

public ref class CObjects : public IList

{

private:

Int items;

array<Object ^> ^ objects;

public:

. . . No Change

virtual int IndexOf(Object ^);

};

. . . No Change

int CObjects::IndexOf(Object ^ value)

{

for(int i = 0; i < Count; i++

if( objects[i] == value ) return i;

return -1;

}

Метод IndexOf() вызывает метод Equals() класса объектов, которые составляют коллекцию. Если имеющаяся реализация метода Equals() не подходит для объектов коллекции, вы должны сделать свою реализацию этого метода.

36.6.6Упражнение: получение индекса элемента

  1. Open the Properties.cpp source file. In the Functions combo box, select IndexOf and implement the method as follows:  

// This method is used to check whether the item passed as

// argument exists in the collection. If so, it returns its index

int CProperties::IndexOf(Object ^ value)

{

int custIndex = -1;

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

{

if( dynamic_cast<CRentalProperty ^>

(this[i])->Equals(dynamic_cast<CRentalProperty ^>(value)) )

{

custIndex = i;

break;

}

}

return custIndex;

}

  1. Open the Exercise.cpp source file and make the following changes:  

#include "RentalProperty.h"

#include "Properties.h"

using namespace System;

Int main()

{

. . . No Change

Console::WriteLine(L"8--8--8--8--8--8--8--8--8--8--8--8--8--8--8");

CRentalProperty ^ item3 = gcnew CRentalProperty;

item3->PropertyCode = 224006;

item3->PropertyType = PropertyTypes::Apartment;

item3->PropertyCondition = PropertyConditions::Excellent;

item3->Bedrooms = 2;

item3->Bathrooms = 1;

item3->MonthlyRent = 1250.55;

Console::WriteLine(L"-=- Sample Property -=-");

Console::WriteLine(L"Property #: {0}", item3->PropertyCode);

Console::WriteLine(L"Property Type: {0}",item3->PropertyType);

Console::WriteLine(L"Condition: {0}", item3->PropertyCondition);

Console::WriteLine(L"Bedrooms: {0}", item3->Bedrooms);

Console::WriteLine(L"Bathrooms: {0}", item3->Bathrooms);

Console::WriteLine(L"Monthly Rent: {0}",item3->MonthlyRent);

Console::WriteLine(L"The index of this property is: {0}",

properties->IndexOf(item3));

Console::WriteLine(L"8--8--8--8--8--8--8--8--8--8--8--8--8--8");

return 0;

}

  1. Execute the application to see the result: 

<+> Solas Properties Rental <+>

<-> Properties Listing <->

---------------------------

1. Property Details

Property #: 737495

Property Type: Apartment

Condition: Good

Bedrooms: 1

Bathrooms: 1

Monthly Rent: 950

---------------------------

2. Property Details

Property #: 293749

Property Type: SingleFamily

Condition: Excellent

Bedrooms: 5

Bathrooms: 3.5

Monthly Rent: 2550.75

---------------------------

3. Property Details

Property #: 224006

Property Type: Apartment

Condition: Excellent

Bedrooms: 2

Bathrooms: 1

Monthly Rent: 1250.55

---------------------------

4. Property Details

Property #: 197249

Property Type: Townhouse

Condition: BadShape

Bedrooms: 4

Bathrooms: 2.5

Monthly Rent: 1750.65

---------------------------

5. Property Details

Property #: 592795

Property Type: SingleFamily

Condition: Good

Bedrooms: 3

Bathrooms: 2

Monthly Rent: 1870.35

================================

8--8--8--8--8--8--8--8--8--8--8--8--8--8--8

-=- Sample Property -=-

Property #: 293749

Property Type: SingleFamily

Condition: Excellent

Bedrooms: 5

Bathrooms: 3.5

Monthly Rent: 2550.75

-------------------------------------------

That property already exists in the listing

8--8--8--8--8--8--8--8--8--8--8--8--8--8--8

-=- Sample Property -=-

Property #: 290004

Property Type: SingleFamily

Condition: Excellent

Bedrooms: 5

Bathrooms: 3.5

Monthly Rent: 0

-------------------------------------------

The property was not found in our database

8--8--8--8--8--8--8--8--8--8--8--8--8--8--8

-=- Sample Property -=-

Property #: 224006

Property Type: Apartment

Condition: Excellent

Bedrooms: 2

Bathrooms: 1

Monthly Rent: 1250.55

The index of this property is: 2

8--8--8--8--8--8--8--8--8--8--8--8--8--8--8

Press any key to continue . . .

  1. Close the DOS window