Yield return: qaytish elementini belgilaydi yield break


Download 63.55 Kb.
bet7/7
Sana24.12.2022
Hajmi63.55 Kb.
#1062569
1   2   3   4   5   6   7
Bog'liq
tsfcsOQYNmo1EkP9FeO7k5euCfrh5g2v

Ishtirokchilar
Iterator: murakkab ob'ektlarni chetlab o'tish uchun interfeysni belgilaydi



  • Aggregate: iterator ob'ektini yaratish uchun interfeysni belgilaydi




  • ConcreteIterator: Aggregate ob'ektini chetlab o'tish uchun maxsus iterator dasturi. Joriy yinelememiş elementning indeksini tuzatish uchun _current tamsayı o'zgaruvchisidan foydalaning




  • ConcreteAggregate: Aggregate-ning aniq amalga oshirilishi. Saralash kerak bo'lgan elementlarni saqlaydi




Endi aniq bir misolni ko'rib chiqing. Aytaylik, bizda kitob darslari va kutubxonalar mavjud:


class Book
{
public string Name { get; set; }
}
class Library
{
private Book[] books;
}
Aytaylik, bizda kutubxonadagi kitoblar haqida ma'lumot olishni istagan o'quvchilar sinfi bor. Va buning uchun iterator yordamida ob'ektlarni sanash kerak:

class Program


{
static void Main(string[] args)
{
Library library = new Library();
Reader reader = new Reader();
reader.SeeBooks(library);
Console.Read();
}
}
class Reader
{
public void SeeBooks(Library library)
{
IBookIterator iterator = library.CreateNumerator();
while(iterator.HasNext())
{
Book book = iterator.Next();
Console.WriteLine(book.Name);
}
}
}
interface IBookIterator
{
bool HasNext();
Book Next();
}
interface IBookNumerable
{
IBookIterator CreateNumerator();
int Count { get; }
Book this[int index] { get;}
}
class Book
{
public string Name { get; set; }
}
class Library : IBookNumerable
{
private Book[] books;
public Library()
{
books = new Book[]
{
new Book{Name="Война и мир"},
new Book {Name="Отцы и дети"},
new Book {Name="Вишневый сад"}
};
}
public int Count
{
get { return books.Length; }
}
public Book this[int index]
{
get { return books[index]; }
}
public IBookIterator CreateNumerator()
{
return new LibraryNumerator(this);
}
}
class LibraryNumerator : IBookIterator
{
IBookNumerable aggregate;
int index=0;
public LibraryNumerator(IBookNumerable a)
{
aggregate = a;
}
public bool HasNext()
{
return index}
public Book Next()
{
return aggregate[index++];
}
}
Download 63.55 Kb.

Do'stlaringiz bilan baham:
1   2   3   4   5   6   7




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling