27-Mavzu. Sinfdagi IEnumerable va IEnumerator interfeysi texnikasining dizaynini o'zgartiring.
Ko'rib turganimizdek, ko'pchilik kollektsiyalarning asosiy qismi IEnumerable va IEnumerator interfeyslarini amalga oshirishdir. Bunday amalga oshirish uchun rahmat foreach tsikli ichida ob'ektlar orqali biz tartiblashtirish mumkin:
o'tish: saytda harakatlanish, qidiruv
{
}
Tartiblangan to'plam IEnumerable interfeysini amalga oshirishi kerak.
IEnumerable interfeysi boshqa interfeysga havola qilish usuliga ega - ro'yxatchi:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
IEnumerator interfeysi konteynerda ichki ob'ektlarni qidirish uchun funksiyalarni belgilaydi:
public interface IEnumerator
{
bool MoveNext(); // element konteynerida oldinga bir joyga ko'chirish
ob'ektni joriy {get;} / / konteynerda mavjud element
void Reset(); // konteyner boshiga ko'chirish
}
MoveNext usuli() ketma-ketlikda keyingi holatda joriy element uchun pointer harakat. Agar ketma-ketlik hali tugamagan bo'lsa, unda
DASTURI:
7-Masala IEnumerable
using System;
using System.Collections;
namespace Rahimjon{
class Week : IEnumerable {
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
public IEnumerator GetEnumerator()
{
return days.GetEnumerator();
}
}
class Program
{
static void Main(string[] args)
{
Week week = new Week();
foreach(var day in week)
{
Console.WriteLine(day);
}
}
}
}
11-Masala IEnumerator
using System;
using System.Collections;
namespace Rahimjon{
class WeekEnumerator : IEnumerator{
string[] days;
int position = -1;
public WeekEnumerator(string[] days)
{
this.days = days;
}
public object Current{
get{
if (position == -1 || position >= days.Length)
throw new InvalidOperationException();
return days[position];
}
}
public bool MoveNext(){
if(position < days.Length - 1)
{
position++;
return true;
}
else
return false;
}
public void Reset() {
position = -1;
}
}
class Week{
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
public IEnumerator GetEnumerator(){
return new WeekEnumerator(days);
}
}
class Program {
static void Main(string[] args) {
Week week = new Week();
foreach(var day in week)
{
Console.WriteLine(day); }
}
}
}
Do'stlaringiz bilan baham: |