gpt4 book ai didi

c# - 调试时,我可以在 LINQ 中查看导致异常的对象吗?

转载 作者:行者123 更新时间:2023-11-30 13:30:12 24 4
gpt4 key购买 nike

假设我有这段代码:

IDictionary<int, int> itemPriceDict = loadItemPriceDictionary();
IList<IRow> dbItems = loadItemsFromDatabase();

IList<ItemDTO> itemDTOs = dbItems
.Select(dbItem => new ItemDTO()
{
Id = dbItem.Id,
Label = dbItem.Label,
PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
})
.ToList();

当给定的价格标签不存在时,我有时会收到 KeyNotFound 异常对于给定的 dbItem。

现在,当在 Visual Studio 中调试并引发异常时,您可以看到 StackTrace 和 TargetSite,它们会告诉您哪一行代码触发了它,但是是否可以找出导致异常的对象 (dbItem) 并在调试器中显示它的数据?例如在 Watch 窗口?

我愿意:

  1. 要么知道哪个键不在字典中
  2. 或者最好知道 key 以及在 Select 中处理的 dbItem

但无需添加或修改任何代码。

P.S.:我知道我可以将代码重写为循环,但我不想这样做。

最佳答案

你可以这样写你的Select:

.Select(dbItem => 
{
return new ItemDTO()
{
Id = dbItem.Id,
Label = dbItem.Label,
PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
})
}
.ToList();

这将允许您在选择的评估中放置断点。

更好的是,进入调试菜单,然后选择异常(它在我的 Visual Studio 版本的 Windows 子菜单下)。

然后对其进行设置,使其在 KeyNotFoundException 或您选择的任何异常时中断。

调试器会在异常发生时自动中断,让您检查相关对象的状态

关于c# - 调试时,我可以在 LINQ 中查看导致异常的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38584305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com