方法语法会阻止隐式转换,但查询语法不会。 Option Strict
已启用。 如何在使用查询语法时强制显示错误?
整个(完全可运行)程序:
Option Strict On
Module Module1
Sub Main()
Dim custList As New List(Of Cust)()
custList.Add(New Cust() With {.Name = "Mr. Current", .Deleted = False})
custList.Add(New Cust() With {.Name = "Mrs. Deleted", .Deleted = True})
custList.Add(New Cust() With {.Name = "Miss Null", .Deleted = Nothing})
Dim QuerySyntax =
From c In custList
Where c.Deleted = False 'no error (the problem)
Dim MethodSyntax =
custList _
.Where(Function(c) c.Deleted = False) 'compiler error (desired effect)
For Each c As Cust In QuerySyntax
Console.WriteLine("Q: " & c.Name & " " & c.Deleted)
Next
For Each c As Cust In MethodSyntax
Console.WriteLine("M: " & c.Name & " " & c.Deleted)
Next
Console.ReadKey(True)
End Sub
Class Cust
Public Property Name() As String
Public Property Deleted() As System.Nullable(Of Boolean)
End Class
End Module
问题关键所在行:
Where c.Deleted = False 'no error
.Where(Function(c) c.Deleted = False) 'compiler error
最佳答案
我将至少采取一些行动,并表示我已经找到了这种行为的解释。
我获取了这段代码,并在QuerySyntax
版本中更改了'c.Deleted = Nothing'
,并立即得到了一个“绿色波浪线”,表示“这个表达式将由于等于运算符的空传播,始终评估为 Nothing。
”这让我思考编译器如何解释表达式,因此我做了更多的窥探,并发现了以下内容:
VB.Net Linq to Entities Null Comparison - 'Is Nothing' or '= Nothing'?
从那篇文章来看,当表达式中涉及 Nullable(Of T)
时,编译器正在内部提升(或者,我想,更准确地说, ,“提升”)将等式运算符转换为 Nullable(Of T) 版本,我认为从技术上讲,这不是“隐式转换”。因此,它不会生成编译时错误。由于该元素作为 parameter
传递给 MethodSyntax
版本中的函数,因此不会应用提升运算符,然后编译器会捕获隐式转换语法。
关于vb.net - 隐式转换 : Nullable(Of T) => T | VB. NET LINQ 查询语法与方法语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30765095/