.Net 【基础回顾】关键字补充yield

yield 关键字

看到这个语法糖很久了,一直也没有在实际中使用,最近在新项目中看到有人用了,还是挺方便的,总结一下使用方法

单词yield有产出,产量的意思,在c#中作为语法糖配合for返回IEnumerable

yield return一次一个的返回

yield break终止迭代

public static IEnumerable<int> Power(int number, int exponent, string s)
{
    int result = 1;

    for (int i = 0; i < exponent; i++)
    {
        result = result * number;
        if(result == 100){
            yield break; //终止
        }
        yield return result; //返回集合的一个元素
    }
    yield return 3;
    yield return 4;
    yield return 5;
}

try-tatch使用时注意点

yield return语句不能位于try-catch

public IEnumerable<string> Test()
{
    try
    {
        for (int i = 0; i < 100; i++)
        {
            yield return (i * 100).ToString();
        }
    }
    catch (Exception ex)
    {
        //yield return "";
        throw;
    }
    finally
    {
        
    }
}

提示错误:

CS1626 无法在包含 catch 子句的 Try 块体中生成值

yield return语句可以位于try-finally的try块

public IEnumerable<string> Test()
{
    try
    {
        for (int i = 0; i < 100; i++)
        {
            yield return (i * 100).ToString();
        }
    }
    //catch (Exception ex)
    //{
    //    //yield return "";
    //    throw;
    //}
    finally
    {

    }
}

这样是可以的

yield break语句可以位于try块或catch块,但是不能位于finally

public IEnumerable<string> Test()
{

    for (int i = 0; i < 100; i++)
    {
        try
        {
            yield break;
        }
        catch (Exception ex)
        {
            yield break;
        }
        finally
        {
            // 错误 CS1625	无法在 finally 子句体中生成
            yield break;
        }

    }
}

posted on 2022-05-03 16:02  杏村牧童  阅读(258)  评论(0编辑  收藏  举报