无法遍历通用迭代函数

时间:2009-11-11 03:49:40

标签: c#

我试图使用C#迭代器遍历整数数组。下面的程序循环遍历非泛型迭代器,但不是通过泛型迭代器。我无法弄清楚问题。

namespace SampleCSApp
{
class Program
{
    static void Main(string[] args)
    {

        var output = new int[10];

        ParallelLoopResult LoopResult = 
        Parallel.For(1, 10, (int i, ParallelLoopState loop) =>
            {
                if (i == 5)
                {
                    loop.Break();
                    return;
                }
                output[i] = Compute(i);
            });

        long CompletedUpto = 10;
        if (!LoopResult.IsCompleted && LoopResult.LowestBreakIteration.HasValue)
            CompletedUpto = LoopResult.LowestBreakIteration.Value;

        string format = string.Format(CompletedUpto == 10 ? "Ran to Completion" : "Completed upto:{0}",CompletedUpto);
        Console.WriteLine(format);

        int index = 0;

        // This does not work.
        foreach (var i in Iterate<int>(() => 0, i => i < output.Length, i => output[i], i => i++))
            Console.WriteLine("output[{0}]:{1}", index++, i);

         // This works.
         foreach(var  i in Iterate(output))
            Console.WriteLine("output[{0}]:{1}", index++, i);
    }

    public static IEnumerable<T> Iterate<T>(Func<T> initialize, Func<T, bool> condition, Func<T, T> body, Func<T, T> update)
    {
        for (T i = initialize(); condition(i); i = update(i))
            yield return body(i);                
    }

    public static IEnumerable<int> Iterate(int[] output)
    {
        for (int i = 0; i < output.Length; i++)
            yield return output[i];
    }

    private static int Compute(int i)
    {
        return i * i;
    }
 }
}

1 个答案:

答案 0 :(得分:3)

我认为后增量是问题吗?

如果你的函数返回i ++,它是否会返回i然后将非共享变量增加?

即将其更改为

i => i + 1

这有帮助吗?