【问题标题】:What is the use of the "yield" keyword in C#? [duplicate]C# 中的“yield”关键字有什么用? [复制]
【发布时间】:2012-07-01 11:24:06
【问题描述】:

可能重复:
Proper Use of yield return

C#中yield关键字有什么用?

我没听懂the MSDN reference... 谁能给我解释一下?

【问题讨论】:

    标签: c# syntax yield-return


    【解决方案1】:

    我会试着给你举个例子

    这是一种经典的做法,它填充一个列表对象,然后返回它:

    private IEnumerable<int> GetNumbers()
    {
        var list = new List<int>();
        for (var i = 0; i < 10; i++)
        {
            list.Add(i);
        }
        return list;
    }
    

    yield 关键字像这样一一返回项目:

    private IEnumerable<int> GetNumbers()
    {
        for (var i = 0; i < 10; i++)
        {
            yield return i;
        }
    }
    

    所以想象一下调用 GetNumbers 函数的代码如下:

    foreach (int number in GetNumbers())
    {
       if (number == 5)
       {
           //do something special...
           break;
       }
    }
    

    如果不使用yield,您必须从0-10 生成整个列表,然后返回该列表,然后迭代直到找到数字5。

    现在多亏了 yield 关键字,您将只生成数字,直到找到您要查找的数字并打破循环。

    我不知道我是否足够清楚..

    【讨论】:

    • 所以yield 只对IEnumerables 有用吗?
    • 你只能在IEnumerables 上使用yield,所以是的
    • @user1480525:但是IEnumerable&lt;T&gt; 可以是任何可能类型的集合,所以你的“just for”是不合适的。
    【解决方案2】:

    我的问题是,我什么时候使用它?有没有什么例子让我别无选择,只能使用产量?为什么有人觉得 C# 需要另一个关键字?

    您链接的文章提供了一个很好的示例,说明了何时以及如何使用它。

    我也讨厌引用你自己链接的一篇文章,但以防它太长,而你没有阅读它。

    yield 关键字向编译器发出信号,表明它出现在其中的方法是一个迭代器块。编译器生成一个类来实现迭代器块中表达的行为。

    public static System.Collections.IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }
    

    在上面的示例中,yield 语句在 迭代器块 中使用。调用 Power 方法时,它返回一个包含数字幂的可枚举对象。请注意,Power 方法的返回类型是 System.Collections.IEnumerable,它是一种迭代器接口类型。

    因此编译器会根据方法执行期间产生的内容自动生成一个 IEnumerable 接口。

    为了完整起见,这里是一个简化的例子:

    public static System.Collections.IEnumerable CountToTen()
    {
        int counter = 0;
        while (counter++ < 10)
        {
            yield return counter;
        }
    }
    
    public static Main(string[]...)
    {
        foreach(var i in CountToTen())
        {
            Console.WriteLine(i);
        }
    }
    

    【讨论】:

    • 所以yield 只对IEnumerables 有用吗?
    猜你喜欢
    • 2014-09-27
    • 2022-11-29
    • 2011-05-18
    • 1970-01-01
    • 2019-09-10
    • 2011-01-17
    • 2019-07-06
    相关资源
    最近更新 更多