.NET - 非常奇怪的NullReferenceException?
在以下场景中如何获得 NullReferenceException
?
Dim langs As IEnumerable(Of SomeCustomObject) = //some LINQ query
If langs Is Nothing Then Return Nothing
If langs.Count = 1 Then //NullReferenceException here
我在这里缺少什么?调试显示 langs
实际上只是一个 LINQ 查询结果,没有任何结果...
How can I get a NullReferenceException
in the following scenario?
Dim langs As IEnumerable(Of SomeCustomObject) = //some LINQ query
If langs Is Nothing Then Return Nothing
If langs.Count = 1 Then //NullReferenceException here
What am I missing here? Debug shows that langs
is really just a LINQ queryresult without any results...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该异常可能来自 LINQ 查询的评估。 LINQ 查询以惰性方式求值:也就是说,在您实际使用该值之前,不会实际执行任何代码。
例如,如果您有以下内容(我不知道 VB 的 LINQ 语法,因此这是 C#,但同样的情况也适用):
此外,您永远不会从创建中返回
null
LINQ 查询的一部分,因此不需要If langs Is Nothing
检查。The exception is probably coming from the evaluation of your LINQ query. LINQ queries are evaluated in a lazy fashion: that is, no code is actually executed until you actually use the value.
For example, if you have the following (I don't know the LINQ syntax for VB, so this is C# but the same thing applies):
Also, you will never get a
null
returned from the creation of the LINQ query so yourIf langs Is Nothing
check is not needed.因为 langs 在被访问之前不会被评估,所以您可以通过转换为列表来强制评估:
Because langs won't be evaluated until it is accessed, you can force the evaluation by converting to a list: