开发者

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

开发者 https://www.devze.com 2023-02-15 11:03 出处:网络
Why does this: Private [Function] As Func(Of Double, String) = Function(ByRef z As Double) z.ToString gives the following error:

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 d开发者_JAVA百科elegate 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?


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()


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消