没有参数的 Lambda 在 VB 中有效,但在 C# 中无效

Lambda with no argument works in VB but not in C#

在VB我可以做到:

Dim a = New Action(Of String)(
        Sub()
            Debug.Print("Hello World.")
        End Sub)

但在 C# 中我不能这样做,这对我来说很有意义,因为 lambda 定义 应该 匹配委托:

var a = new Action<string>(() => 
{
    System.Diagnostics.Debug.Print("Hello World.");
});

不能在VB中这样做,这是有道理的。

Dim a = New Action(
        Sub(x As String)
            Debug.Print("Hello World.")
        End Sub)

那么,为什么 VB 允许一种异常情况,在这种情况下,您可以提供不带任何参数但似乎与委托不兼容的 lambda 表达式?

Relaxed Delegate Conversion (Visual Basic)

Relaxed delegate conversion enables you to assign subs and functions to delegates or handlers even when their signatures are not identical. Therefore, binding to delegates becomes consistent with the binding already allowed for method invocations.

(...)

Relaxed delegates also allow you to completely omit parameter specifications in the assigned method:

它还描述了可能有用的原因:

The ability to omit parameters is helpful in a situation such as defining an event handler, where several complex parameters are involved. The arguments to some event handlers are not used. Instead, the handler directly accesses the state of the control on which the event is registered, and ignores the arguments. Relaxed delegates allow you to omit the arguments in such declarations when no ambiguities result. In the following example, the fully specified method OnClick can be rewritten as RelaxedOnClick.