为什么没有捕获到 RuntimeBinderException?
Why RuntimeBinderException is not caught?
我明白为什么它会被抛出,但是为什么当我有一个 catch 块时它仍然没有得到处理?详情请见附图。
try
{
// Exception is thrown at the following line as not all items have Id property
addedLabours = currentLabours.Where(c => !previousLabours.Select(p => (Guid)p.Id).Contains((Guid)c.Id));
}
catch (RuntimeBinderException)
{
addedLabours = currentLabours;
}
我刚从我的一位同事那里得到答案:
“因为它是延迟执行。lamba 在此上下文之外执行,因为在深处仍然存在 IQueryables。IQueryables 的基础是一个构造但在不同点执行的表达式。
如果 where 子句中的 lamba 位于 {} 内,您可以放置 try {} catch (RuntimeBinderException),它会被捕获。但不在兰巴之外。"
除了理解可以通过附加 .ToList()
来捕获它的原因(感谢 Hans Passant!)。
try
{
// Exception will be caught with .ToList()
addedLabours = currentLabours.Where(c => !previousLabours.Select(p => (Guid)p.Id).Contains((Guid)c.Id)).ToList();
}
catch (RuntimeBinderException)
{
addedLabours = currentLabours;
}
我明白为什么它会被抛出,但是为什么当我有一个 catch 块时它仍然没有得到处理?详情请见附图。
try
{
// Exception is thrown at the following line as not all items have Id property
addedLabours = currentLabours.Where(c => !previousLabours.Select(p => (Guid)p.Id).Contains((Guid)c.Id));
}
catch (RuntimeBinderException)
{
addedLabours = currentLabours;
}
我刚从我的一位同事那里得到答案:
“因为它是延迟执行。lamba 在此上下文之外执行,因为在深处仍然存在 IQueryables。IQueryables 的基础是一个构造但在不同点执行的表达式。
如果 where 子句中的 lamba 位于 {} 内,您可以放置 try {} catch (RuntimeBinderException),它会被捕获。但不在兰巴之外。"
除了理解可以通过附加 .ToList()
来捕获它的原因(感谢 Hans Passant!)。
try
{
// Exception will be caught with .ToList()
addedLabours = currentLabours.Where(c => !previousLabours.Select(p => (Guid)p.Id).Contains((Guid)c.Id)).ToList();
}
catch (RuntimeBinderException)
{
addedLabours = currentLabours;
}