谁能告诉我Func
之间有什么区别?和 Function
在 VB 中。
例如,请参阅以下内容:
Dim F As Func(Of String) = Function() As String
Return "B"
End Function
Dim F2 = Function() As String
Return "B"
End Function
F
显示为 Func(Of String)
F2
作为 Function() As String
. 看起来他们做同样的事情,但考虑到编译器认为他们有不同的类型,肯定有微妙之处。
最好的祝福
查尔斯
最佳答案
Func(Of TResult)()
是一个名为 Func
的特定代表.它是在 System
中声明的类型命名空间如下:
Public Delegate Function Func(Of TResult)() As TResult
它可能有不同的命名。例如:
Public Delegate Function MyParameterLessFunction(Of TResult)() As TResult
所以
Func
实际上只是给代表的名字。由于 F2
的类型没有明确指定,VB 不知道这个委托(delegate)的名称。是Func
或 MyParameterLessFunction
或者是其他东西?相反,VB 只显示其签名 Function() As String
, 自 F2
也适合声明为的非泛型委托(delegate)Public Delegate Function AnonymousParameterLessStringFunction() As String
在您的评论中,您使用
.ToString()
在 F
和 F2
.这将返回运行时类型,即分配给这些变量的值的类型。这些类型可以不同于这些变量的静态类型,即赋予变量名称的类型。让我们做一个小测试Imports System.Reflection
Module FuncVsFunction
Dim F As Func(Of String) = Function() As String
Return "B"
End Function
Dim F2 = Function() As String
Return "B"
End Function
Sub Test()
Console.WriteLine($"Run-time type of F: {F.ToString()}")
Console.WriteLine($"Run-time type of F2: {F2.ToString()}")
Dim moduleType = GetType(FuncVsFunction)
Dim fields As IEnumerable(Of FieldInfo) = moduleType _
.GetMembers(BindingFlags.NonPublic Or BindingFlags.Static) _
.OfType(Of FieldInfo)
For Each member In fields
Console.WriteLine($"Static type of {member.Name}: {member.FieldType.Name}")
Next
Console.ReadKey()
End Sub
End Module
它显示
Run-time type of F: System.Func`1[System.String]
Run-time type of F2: VB$AnonymousDelegate_0`1[System.String]
Static type of F: System.Func`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Static type of F2: System.Object
请注意
F2
只需键入 Object
.这是一个惊喜。我希望它是一个委托(delegate)类型。您还可以在调试器中看到这种差异。如果在
Test
中设置断点方法,然后将鼠标悬停在 Dim
F
的关键词和 F2
,弹出窗口显示'Dim of F (static type)
Delegate Function System.Func(Of Out TResult)() As String
'Dim of F2 (static type)
Class System.Object
如果将鼠标悬停在变量名称上
'F (run-time type)
Method = {System.String _Lambda$__0-0()}
'F2 (run-time type)
<generated method>
对于
F
您不仅可以获得类型信息,还可以获得生成的方法本身的名称。由于F2
是一个对象,Visual Studio 显然没有像 F
那样深入挖掘。 .
关于vb.net - VB中的函数与函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17469541/