用作参数时无法推断 Action 委托的返回类型

con*_*att 4 .net c# vb.net

我在VB.NET中有以下方法:

Private Sub DelegateTest(ByVal doSomething As Action(Of TrimEntry))
    doSomething(New TrimEntry())
End Sub
Run Code Online (Sandbox Code Playgroud)

以下尝试调用该方法会导致编译时错误无法推断返回类型。考虑添加“As”子句来指定返回类型。。(为了简洁起见,我省略了一些代码,但我的调用需要的不仅仅是一行语句。)

DelegateTest(Function(item)
                 item.Length = 0
             End Function)
Run Code Online (Sandbox Code Playgroud)

也许我被 C# 宠坏了,但在 C# 中它非常简单。

DelegateTest(item => { item.Length = 0; })
Run Code Online (Sandbox Code Playgroud)

问题: 为什么会出现这个错误?我很困惑,因为该类型是一个 Action 委托,它返回 void。为什么我会收到返回类型错误?

Ser*_*rvy 5

由于您的匿名方法没有返回值,Sub因此您需要使用Function.