, .
// .
Using System;
Using System.Collections;
class MyClass { char ch = 'A';
// 10 , public IEnumerator GetEnumerator() {
for(int i=0; i < 26; i++) {
if(i == 10) yield break; // yield return (char) (ch + i);
}
}
}
class ItrDemo3 {
static void Main() {
MyClass me = new MyClass();
Foreach(char ch in me)
Console.Write(ch + " ");
Console.WriteLine();
}
}
.
ABCDEFGHIJ
yield
yield. . .
// yield.
Using System;
Using System.Collections;
class MyClass {
// , , , D . public IEnumerator GetEnumerator() {
yield return 'A'; yield return 'B'; yield return 'C'; yield return 'D'; yield return 'E';
}
}
class ItrDemo5 {
static void Main() {
MyClass me = new MyClass();
Foreach(char ch in me)
Console.Write(ch + " ");
Console.WriteLine();
}
}
.
D
GetEnumerator () yield. , , . , foreach Main () .
. . , ,
I Enumerable. . , :
public IEnumerable _ (_) {
//...
yield return obj;
}
_ ; _ , ; obj , . , , ,
Foreach.
, , . , , . , . . , .
|
|
// .
Using System;
Using System.Collections;
class MyClass { char ch = 'A';
// ,
}
}
class ItrDemo4 {
static void Main() {
MyClass me = new MyClass ();
Console.WriteLine(" 7 :"); foreach(char ch in mc.MyItr(7))
Console.Write(ch + " ");
Console.WriteLine (lf\nlf);
Console.WriteLine(" F L:"); foreach(char ch in mc.Myltr(5, 12))
Console.Write(ch + " ");
Console.WriteLine();
}
}