问题描述
以下代码段旨在在枚举时捕获所有异常,并忽略该特定项。
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
DataProvider[] dataproviders = new DataProvider[]
{
new DataProvider(itemCount: 3,throwAfter: 1),new DataProvider(itemCount: 4),};
var output = ListEnumerable(dataproviders).ToList();
// We'll never get there. I excepted items from second dataprovider here
Console.WriteLine("Success");
}
private static IEnumerable<Item> ListEnumerable(IEnumerable<DataProvider> providers)
{
ArgumentException providerException = null;
foreach (DataProvider provider in providers)
{
providerException = null;
try
{
return provider.GetData();
}
catch (ArgumentException ex)
{
// Expected to catch the argumentexception thrown in GetData here. This never happens
providerException = ex;
Console.WriteLine("Exception caught");
}
}
if (providerException != null)
{
throw providerException;
}
return Enumerable.Empty<Item>();
}
private class DataProvider
{
public DataProvider(int itemCount = 3,int throwAfter = -1)
{
this.ItemCount = itemCount;
this.ThrowAfter = throwAfter;
}
public int ItemCount { get; }
public int ThrowAfter { get; }
public IEnumerable<Item> GetData()
{
for (int i = 0; i < this.ItemCount; ++i)
{
if (i == this.ThrowAfter)
{
throw new ArgumentException("Thrown after " + i);
}
yield return new Item();
}
}
}
private class Item
{
public string Name = Guid.NewGuid().ToString();
}
}
我希望在ListEnumerable
中引发异常,然后转到下一项。但是,运行摘要会导致在main中引发异常。
为什么会这样?用懒惰的评估仍然完整的数据来表达这一点的正确方法是什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)