跟进 R# 警告:可能的“System.InvalidOperationException”
我有以下表达式,其中 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您在
Where
中检查a.AnswerId
有一个值,因此a.AnswerId.Value
永远不会抛出InvalidOperationException
code> (除非另一个线程同时更改数据)。 Resharper 具有相当不错的代码分析功能,但它无法发现所有内容,在这种情况下,它没有意识到Where
可以安全地调用.Value
Select
,因此出现警告。因此您可以安全地忽略此警告。Since you check in the
Where
thata.AnswerId
has a value,a.AnswerId.Value
will never throw anInvalidOperationException
(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 theWhere
makes it safe to call.Value
in theSelect
, hence the warning. So you can safely ignore this warning.不幸的是,ReSharper 经常出现误报。在这种情况下,只要
AnswerId
在调用Where
和Select
时返回相同的值就不会出现问题。 (确保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 toWhere
andSelect
. (Make sureAnswerId
doesn’t have some crazy implementation that returns a number the first time you access it andnull
the second time.)遗憾的是,ReSharper 无法通过 LINQ lambda 序列跟踪条件检查。这是一个已知问题。
Unfortunately, ReSharper cannot track condition checks through LINQ lambdas sequence. This is a known problem.