拜尔:
Public Sub foo()
bar(AddressOf baz)
End Sub
Public Sub bar(ByVal numFun As Action(Of Integer))
End Sub
Public Sub baz(ByVal num As Integer)
End Sub
引用:
Public Sub foo()
bar(AddressOf baz)
End Sub
Public Sub bar(ByVal numFun As Action(Of Integer))
End Sub
Public Sub baz(ByRef num As Integer)
' num has been changed to ByRef above ^^^
End Sub
上面没问题,不会导致错误。但是,如果参数更改为 ByRef,如下所示,它会抛出以下错误:
Error: Method 'Public Sub baz(ByRef Integer)' does not have a signature compatible with delegate 'Public Delegate Sub Action(Of In Integer)(Integer)'
它在错误中给出的签名与我所拥有的完全不匹配 - 什么是“(Of In Integer)(Integer)”?我没有实例化任何东西。为什么是“在”?无论如何,我真正想要的是如何使它工作。我无法更改必须保留的 ByRef。
***注意:我知道我可以创建一个显式委托(delegate),但我不想这样做,因为在整个代码中我有几个这个问题的实例,而且这似乎是不必要的开销。
提前致谢
最佳答案
Delegate Sub MyAction(Of T)(ByRef num As T)
Public Sub foo()
bar(AddressOf baz)
End Sub
Public Sub bar(numFun As MyAction(Of Integer))
End Sub
Public Sub baz(ByRef num As Integer)
' num has been changed to ByRef above ^^^
End Sub
更新
无法绕过声明您的 ByRef
Delegate
。这是 System.Action(Of T)
的定义:
Public Delegate Sub Action(Of In T)(obj As T)
因此您不能将 System.Action
用于 ByRef
参数,因为它已被声明为 ByVal
。
关于vb.net - 当 T 是 ByRef 时如何传递一个 Action(Of T),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42845519/