第 4 行和第 5 行之间有什么区别吗?
为什么 VB.net 不能处理第 3 行?
调用函数的正确方法是什么?
Dim aFunc As New Tuple(Of Func(Of String))(Function() "Hello World")
Dim s As String
s = aFunc.Item1() 'does not compile
s = (aFunc.Item1)()
s = aFunc.Item1.Invoke()
第 4 行和第 5 行之间有什么区别吗?
为什么 VB.net 不能处理第 3 行?
调用函数的正确方法是什么?
Dim aFunc As New Tuple(Of Func(Of String))(Function() "Hello World")
Dim s As String
s = aFunc.Item1() 'does not compile
s = (aFunc.Item1)()
s = aFunc.Item1.Invoke()
对我来说,这看起来像是一个编译器错误,括号应该明确地使它成为一个方法调用。很难说这是一个事实,然而,在 vb.net 中括号严重超载意味着很多事情。显然是元组使编译器出错,没有它它也能正常工作。这出现在本周与 Eric Lippert 的 StackExchange 播客中,顺便说一句,您可能想听听它以获取它可能意味着的事情的洗衣清单。
您可以将此发布到 connect.microsoft.com 以获得语言设计者的意见。这种行为肯定不够直观,足以称其为错误。您找到的解决方法很好。两者都生成完全相同的代码并且不增加任何开销,您可以通过在程序集上运行 ildasm.exe 看到这一点。
aFunc.Item1
是一个函数,所以你不能将它分配给一个字符串。你似乎想要:
Dim aFunc As New Tuple(Of Func(Of String))(Function() "Hello World")
Dim s As String
Dim f As Func(Of String) = aFunc.Item1
s = f.Invoke()
编辑:
s = aFunc.Item1()
访问属性Item1
。要调用该属性所引用的函数,您可以使用s = aFunc.Item1()()
,这相当于您的第 4 行。猜测,属性访问比函数调用强(如果这些是正确的术语)。