bool TryDequeue(out T natijasi) : navbatning birinchi elementini navbatdan olib tashlash bilan o'zgaruvchan natijaga o'tkazadi, trueagar navbat bo'sh bo'lmasa va element muvaffaqiyatli qabul qilingan bo'lsa, qaytaradi.
bool TryPeek(out T result) : navbatning birinchi elementini navbatdan olib tashlamasdan o'zgaruvchan natijaga o'tkazadi, trueagar navbat bo'sh bo'lmasa va element muvaffaqiyatli olinsa, qaytaradi.
Qo'llash usullari:
|
var people = new Queue();
// elementlarni qo'shish
people.Enqueue("Tom"); // people = { Tom }
// elementlarni olib tashlash
var success1 = people.TryDequeue(out var person1); // success1 = true
if (success1) Console.WriteLine(person1); // Tom
var success2 = people.TryPeek(out var person2); // success2 = false
if (success2) Console.WriteLine(person2);
|
Navbatlar haqiqiy hayotda juda keng tarqalgan tuzilmadir. Masalan, shifokorga murojaat qilish uchun bemorlarning navbati. Keling, ushbu vaziyatni amalga oshiramiz:
|
var patients = new Queue
();
patients.Enqueue(new Person("Tom"));
patients.Enqueue(new Person("Bob"));
patients.Enqueue(new Person("Sam"));
var practitioner = new Doctor();
practitioner.TakePatients(patients);
class Person
{
public string Name { get; }
public Person(string name) => Name = name;
}
class Doctor
{
public void TakePatients(Queue
patients)
{
while(patients.Count > 0)
{
var patient = patients.Dequeue();
Console.WriteLine($"Bemorni tekshirish {patient.Name}");
}
Console.WriteLine("Shifokor bemorlarni tekshirishni tugatdi");
}
}
|
Bu yerda shifokor sinfi - TakePatient usulidagi Doctor sinfi Person ob'ektlari ko'rinishidagi bemorlarning navbatini oladi. Navbatda ob'ektlar mavjud bo'lsa-da, u bir vaqtning o'zida bitta ob'ektni chiqaradi. Konsol chiqishi:
|