Func(Of Tin, Tout) using a lambda expression with ByRef argument gives incompatible signature error

跟風遠走 提交于 2019-12-05 18:24:51

问题


Why does this:

Private [Function] As Func(Of Double, String) = Function(ByRef z As Double) z.ToString

gives the following error:

Nested function does not have a signature that is compatible with delegate String)'.

While this:

Private [Function] As Func(Of Double, String) = Function(ByVal z As Double) z.ToString

Does not? (The difference is ByRef/ByVal)

Furthermore, how might I implement such a thing?


回答1:


You are getting this error because the delegate type Function (ByVal z As Double) As String is not compatible with Function (ByRef z As Double) As String. You need exact match.

Also you can't declare the Func(Of ...) generic delegate with ByRef parameters (ref or out in C#), no matter are you using anonymous function or not.

But you can declare you delegate type and then use it even with your anonymous function

Delegate Function ToStringDelegate(ByRef value As Double) As String

Sub Main()
    Dim Del As ToStringDelegate = Function(ByRef value As Double) value.ToString()
End Sub

or you can use implicit typing (if the Option Infer is turned on)

Dim Del = Function(ByRef value As Double) value.ToString()



回答2:


On MSDN it mentions the following rules apply to variable scope in lambda expressions:

  • A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
  • Variables introduced within a lambda expression are not visible in the outer method.
  • A lambda expression cannot directly capture a ref [ByRef in VB] or out parameter from an enclosing method.
  • A return statement in a lambda expression does not cause the enclosing method to return.
  • A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.


来源:https://stackoverflow.com/questions/5240096/funcof-tin-tout-using-a-lambda-expression-with-byref-argument-gives-incompati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!