跟进 R# 警告:可能的“System.InvalidOperationException”

发布于 2024-12-28 04:33:21 字数 329 浏览 0 评论 0原文

我有以下表达式,其中 a.AnswerId 的类型为 long?。 ReSharper 警告 select 函数中可能存在 InvalidOperationException。有没有这种情况真的可能发生的情况? (极端情况也很好)

long[] ids = answers.Where(a => a.AnswerId.HasValue)
                    .Select(a => a.AnswerId.Value)
                    .ToArray();

I have the following expression, where a.AnswerId is of type long?. ReSharper warns of a possible InvalidOperationException in the select function. Is there ever a case where this could actually happen? (corner-cases are fine too)

long[] ids = answers.Where(a => a.AnswerId.HasValue)
                    .Select(a => a.AnswerId.Value)
                    .ToArray();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笑梦风尘 2025-01-04 04:33:21

由于您在 Where 中检查 a.AnswerId 有一个值,因此 a.AnswerId.Value 永远不会抛出 InvalidOperationException code> (除非另一个线程同时更改数据)。 Resharper 具有相当不错的代码分析功能,但它无法发现所有内容,在这种情况下,它没有意识到 Where 可以安全地调用 .Value Select,因此出现警告。因此您可以安全地忽略此警告。

Since you check in the Where that a.AnswerId has a value, a.AnswerId.Value will never throw an InvalidOperationException (unless another thread is changing the data at the same time). Resharper has pretty good code analysis capabilities, but it can't spot everything, and in this case it doesn't realize that the Where makes it safe to call .Value in the Select, hence the warning. So you can safely ignore this warning.

自我难过 2025-01-04 04:33:21

不幸的是,ReSharper 经常出现误报。在这种情况下,只要 AnswerId 在调用 WhereSelect 时返回相同的值就不会出现问题。 (确保 AnswerId 没有一些疯狂的实现,在您第一次访问它时返回一个数字,而在第二次访问时返回 null。)

Unfortunately, ReSharper often comes up with false positives. In this case, there won’t be a problem as long as AnswerId returns the same value in the calls to Where and Select. (Make sure AnswerId doesn’t have some crazy implementation that returns a number the first time you access it and null the second time.)

み零 2025-01-04 04:33:21

遗憾的是,ReSharper 无法通过 LINQ lambda 序列跟踪条件检查。这是一个已知问题。

Unfortunately, ReSharper cannot track condition checks through LINQ lambdas sequence. This is a known problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文