C# 0 The Complete Reference


Creating a Generic Iterator



Download 4,07 Mb.
Pdf ko'rish
bet1014/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   1010   1011   1012   1013   1014   1015   1016   1017   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt

Creating a Generic Iterator

The preceding examples of iterators have been non-generic, but it is, of course, also possible 

to create generic iterators. Doing so is quite easy: Simply return an object of the generic 

IEnumerator

 or 


IEnumerable

 type. Here is an example that creates a generic iterator:

// A simple example of a generic iterator.

using System;

using System.Collections.Generic;

class MyClass {

  T[] array;

  public MyClass(T[] a) {

    array = a;

  }


  // This iterator returns the characters

  // in the chrs array.

  public IEnumerator GetEnumerator() {

    foreach(T obj in array)

      yield return obj;

  }


}

class GenericItrDemo {

  static void Main() {

    int[] nums = { 4, 3, 6, 4, 7, 9 };

    MyClass mc = new MyClass(nums);

    foreach(int x in mc)

      Console.Write(x + " ");

    Console.WriteLine();

    bool[] bVals = { true, true, false, true };

    MyClass mc2 = new MyClass(bVals);

    foreach(bool b in mc2)

      Console.Write(b + " ");

    Console.WriteLine();

  }


}

The output is shown here:

4 3 6 4 7 9

True True False True

In this example, the array containing the objects to be iterated is passed to 

MyClass

through its constructor. The type of the array is specified as a type argument to 



MyClass

.

www.freepdf-books.com




Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   1010   1011   1012   1013   1014   1015   1016   1017   ...   1096




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

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish