使用C#延迟执行 [英] Deferred execution with C#

查看:116
本文介绍了使用C#延迟执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
i was watching a video that was a simulation of where and select expression of linq to objects with extension methods and here is the code

using System;
using System.Collections.Generic;
public static class Program
{
    static IEnumerable<T> Where<T>(this IEnumerable<T> items, Func<T, bool> gauntlet)
    {
        Console.WriteLine("where");
        foreach (T item in items)
        {
            if (gauntlet(item))
                yield return item;
        }
    }

    static IEnumerable<R> Select<T,R>(this IEnumerable<T> items, Func<T, R> transform)
    {
        Console.WriteLine("select");
        foreach (T item in items)
                yield return transform(item);
 
    }
    static void Main()
    {
        int[] stuff = { 4, 8, 1, 9 };
        IEnumerable<int> result =
            stuff
            .Where(i => i < 5)
            .Select(i => i);

        IEnumerator<int> rator = result.GetEnumerator();

        while (rator.MoveNext())
            Console.WriteLine(rator.Current);
        Console.ReadLine();
    }  
}

when i run this code i get the  following output
select
where
4
1

but i expect this output to be 
where
select
4
1

so i bet  the yield keyword is cooking something somewhere so would plz explain to me why is it happening from the end to the beginning? and not vice versa and the role of yield in there?





我尝试了什么:



i试图了解这段代码,但我可以不是



What I have tried:

i tried to understand this code but i could not

推荐答案

你可能会想到Linq操作返回IEnumerable-something-or-others作为返回如何组装最终的实际结果......这就是延期部分。什么触发评估并返回实际结果可以通过ToArray,ToList,ToDictionary运算符转换为Array,List或Dictionary,或者,它可以通过迭代其内容枚举 IEnumerable有一个for循环,一个for-each循环等等。



这里有一种语义重叠,有些人觉得很困惑,因为我们习惯了I-something - 或其他人是接口,并且IEnumerable具有接口不共享的附加行为级别,以及它们两者的共同因素,在某种程度上,抽象。
It may be useful for you to think of Linq operations that return IEnumerable-something-or-others as returning a kind of "abstract map" of how to assemble the eventual "actual" result ... that's the "deferred" part. What triggers evaluation and returns the "actual" result can be conversion to Array, or List, or Dictionary via the ToArray, ToList, ToDictionary operators, or, it can be enumerating the IEnumerable through iterating over its contents with a for-loop, a for-each loop, etc.

There is a kind of semantic overlap here that some find confusing because we are used to I-something-or-others being Interfaces, and IEnumerable has an additional level of behavior that Interfaces do not share, as well as the common factor that they are both, in a way, "abstractions."


请参阅 yield(C#参考) [ ^ ]。


这篇关于使用C#延迟执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆