这是一个简洁的小方法,只要您迭代IEnumerable
.
public IEnumerable<int> Twist(int min, int max) {
Random random = new Random();
int result = 0;
while (true) {
result += random.Next(min, max); // overflow pretty likely for large max
System.Diagnostics.Debug.WriteLine(result);
yield return result;
}
}
// For a single element
int oneResult = Twist(1, 5).First();
// For the fifth
int fifth = Twist(1, 5).Skip(4).First();
如果您想推迟迭代,请为自己定义一个不错的扩展方法:
public static class EnumeratorExt {
public static T Next<T> (this IEnumerator<T> seq) {
if (seq.MoveNext()) {
return seq.Current;
}
return default(T);
}
}
// Now call it like so!
using (var generator = Twist(5, 10).GetEnumerator()) {
Console.WriteLine(generator.Next());
Console.WriteLine(generator.Next());
Console.WriteLine(generator.Next());
Console.WriteLine(generator.Next());
}