如果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)