25.07.2017 Views

Intro-CSharp-Book-v2015

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

612 Въведение в програмирането със C#<br />

public AnimalShelter(int placesCount)<br />

{<br />

this.animalList = new T[placesCount];<br />

this.usedPlaces = 0;<br />

}<br />

public void Shelter(T newAnimal)<br />

{<br />

if (this.usedPlaces >= this.animalList.Length)<br />

{<br />

throw new InvalidOperationException("Shelter is full.");<br />

}<br />

this.animalList[this.usedPlaces] = newAnimal;<br />

this.usedPlaces++;<br />

}<br />

public T Release(int index)<br />

{<br />

if (index < 0 || index >= this.usedPlaces)<br />

{<br />

throw new ArgumentOutOfRangeException(<br />

"Invalid cell index: " + index);<br />

}<br />

T releasedAnimal = this.animalList[index];<br />

for (int i = index; i < this.usedPlaces - 1; i++)<br />

{<br />

this.animalList[i] = this.animalList[i + 1];<br />

}<br />

this.animalList[this.usedPlaces - 1] = null;<br />

this.usedPlaces--;<br />

}<br />

}<br />

return releasedAnimal;<br />

Всичко изглежда наред, докато не се опитаме да компилираме класа.<br />

Тогава получаваме следната грешка:<br />

Cannot convert null to type parameter 'T' because it could be a nonnullable<br />

value type. Consider using 'default(T)' instead.<br />

Грешката е в метода Release() и е свързана със записването на резултат<br />

null в освободената последна (най-дясна) клетка на приюта. Проблемът е,<br />

че се опитваме да използваме подразбиращата се стойност за референтен<br />

тип, но не сме сигурни, дали конкретния тип е референтен или примитивен.<br />

Тъкмо затова, компилаторът извежда гореописаните грешки. Ако типът<br />

AnimalShelter се инстанцира по структура, а не по клас, то стойността null<br />

е невалидна.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!