In javascript I can create a generator which would behave like this:
function* idMaker(){
var index = 0;
while(true)
yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
What would the C# equivalent look like?
I wonder whether this will work:
static System.Collections.Generic.IEnumerable<int> MakeId()
{
int index = 0;
while (true)
yield return index++;
}
but from what I understand of C# so far, the above wouldn't work as I intend and instead infinite loop.
You can do the same with your MakeId in the following way:
using (var gen = MakeId().GetEnumerator()) {
gen.MoveNext();
Console.WriteLine(gen.Current); // 0
gen.MoveNext();
Console.WriteLine(gen.Current); // 1
gen.MoveNext();
Console.WriteLine(gen.Current); // 2
}
If you don't like to call MoveNext
all the time, you can write extension method:
public static class Extensions {
public static T NextValue<T>(this IEnumerator<T> enumerator) {
enumerator.MoveNext();
return enumerator.Current;
}
}
Then it becomes
using (var gen = MakeId().GetEnumerator()) {
Console.WriteLine(gen.NextValue()); // 0
Console.WriteLine(gen.NextValue()); // 1
Console.WriteLine(gen.NextValue()); // 2
}
Well, the C#
equivalent to your code is:
static void Main()
{
var enumerator = MakeId().GetEnumerator();
enumerator.MoveNext();
Console.WriteLine(enumerator.Current); // 0
enumerator.MoveNext();
Console.WriteLine(enumerator.Current); // 1
enumerator.MoveNext();
Console.WriteLine(enumerator.Current); // 2
}
static IEnumerable<int> MakeId()
{
int index = 0;
while (true)
yield return index++;
}
GetEnumerator
returns an enumerator that iterates through a collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.