小编Raf*_*het的帖子

为什么在c#中使用"yield"关键字进行延迟执行会有不同的运行时行为?

如果IgnoreNullItems在下面的sammple代码中调用扩展方法,则延迟执行按预期工作,但是在使用时IgnoreNullItemsHavingDifferentBehaviour会立即引发异常.为什么?

List<string> testList = null;
testList.IgnoreNullItems(); //nothing happens as expected

testList.IgnoreNullItems().FirstOrDefault();
//raises ArgumentNullException as expected

testList.IgnoreNullItemsHavingDifferentBehaviour(); 
//raises ArgumentNullException immediately. not expected behaviour -> 
//  why is deferred execution not working here?
Run Code Online (Sandbox Code Playgroud)

感谢您分享您的想法!

Raffael Zaghet

public static class EnumerableOfTExtension
{
    public static IEnumerable<T> IgnoreNullItems<T>(this IEnumerable<T> source)
        where T: class
    {
        if (source == null) throw new ArgumentNullException("source");

        foreach (var item in source)
        {
            if (item != null)
            {
                yield return item;
            }
        }
        yield break;
    }

    public …
Run Code Online (Sandbox Code Playgroud)

.net c# yield keyword deferred-execution

1
推荐指数
1
解决办法
322
查看次数

标签 统计

.net ×1

c# ×1

deferred-execution ×1

keyword ×1

yield ×1