.net – 在VB中的If()函数和委托

在VB2012中使用以下代码,我希望将foo初始化为Nothing:

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

但是,它会抛出ArgumentException:

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

我不太明白这个错误消息,但如果我将foo的类型更改为Func(Of Integer,Integer),情况就会变得非常可怕.在这种情况下,代码运行时没有错误,但是foo变成了一个神秘的lambda表达式,在调用时会抛出NullReferenceException.

如果我使用传统的If语句而不是If函数,代码将按预期工作.

有人可以向我解释这种行为吗?

最佳答案 看起来像IIf工作正常:

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)

无论如何都会抛出异常.

点赞