Function () and delegates in VB

Taking the following code in VB2012, I expect foo to be initialized to Nothing:

 Dim foo As Func(Of Integer) = If(True, Nothing, Function() 0)

However, it throws an ArgumentException:

Delegate to an instance method cannot have null 'this'.

I don’t quite understand this error message, but the situation becomes intimidating if I change the type of foo to Func (Of Integer, Integer). In this case, the code works without errors, but foo becomes a mysterious lambda expression that throws a NullReferenceException when called.

If I use the traditional if statement instead of the If function, the code works as expected.

Can someone explain this behavior to me?

+4
source share
2 answers

Looks like it IIfworks fine:

Dim foo As Func(Of Integer) = IIf(True, Nothing, Function() 0)

, , .

, , . :

Dim foo As Func(Of Integer) = New Func(Of Integer)(Nothing.Invoke)

.

True

Dim t = Integer.Parse(Console.ReadLine()) < 10
Dim foo As Func(Of Integer) = If(t, Nothing, Function() 0)

:

Dim foo As Func(Of Integer) = New Func(Of Integer)((If((Integer.Parse(Console.ReadLine()) < 10), Nothing, New VB$AnonymousDelegate_0(Of Integer)(Nothing, ldftn(_Lambda$__1)))).Invoke)

.

+1

, , :

Dim f As Func(Of Integer) = Function() 0
Dim foo As Func(Of Integer) = If(True, Nothing, f)

, :

Dim foo As Func(Of Integer) = If(True, Nothing, Function() Nothing)

(Nothing 0).

- - , , , . , :

Dim foo As Func(Of Integer) = If(True, Nothing, Nothing)

True True, , .

+1

Source: https://habr.com/ru/post/1524888/


All Articles