在 VB 中我可以这样做:
Dim a = New Action(Of String)(
Sub()
Debug.Print("Hello World.")
End Sub)
但在 C# 中我不能这样做,这对我来说很有意义,因为 lambda 定义应该匹配委托(delegate):
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 允许这种异常情况,您可以提供一个不带参数但看起来与委托(delegate)不兼容的 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.
关于c# - 没有参数的 Lambda 在 VB 中有效,但在 C# 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929337/