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

标签 c# vb.net lambda delegates

在 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/

相关文章:

c# - Azure Blob 存储下载文件而不是在浏览器中打开

c# 文本框到数据库

.net - Crystal Reports 2008 和 .mdf 文件有哪些先决条件

c++ - 如何制作一个函数模板,它接受一个带有可变参数的仿函数

c# - 在两种语言通用的 Java 和 C# 中生成 key

c# - 从托管 C++/CLI 线程调用静态 C# 方法

asp.net - Insert 方法触发后,如何防止 FormView 清除用户输入的值?

vb.net - 使用 VB.NET 创建能够进行每次循环的 COM 类

Java 8 使用过滤器选项在嵌套列表中执行求和运算

c# - 使用 c# lambda 将 NameValueCollection 转换为查询字符串是否有效?