VB.NET匿名委托的等效C#代码是什么?

Jes*_*fon 1 .net c# vb.net delegates anonymous

以下VB.NET的等效C#代码是什么:

Dim moo = Function(x as String) x.ToString()

我认为这应该有效:

var moo = (string x) => x.ToString();

但是这产生了一个编译器错误: Cannot assign lamda expression to an implicitly-typed local variable

经过一些进一步的调查,我发现VB示例中的variable moo(moo.GetType())类型是VB$AnonymousDelegate_0'2[System.String,System.String]

在C#中有没有相同的东西?

Ser*_*rvy 5

lambda需要推断从其上下文中使用的委托的类型.隐式类型变量将从分配给它的内容中推断出它的类型.他们每个人都试图从另一个推断他们的类型.您需要在某处明确使用该类型.

有很多代表可以拥有您正在使用的签名.编译器需要某种方式来知道使用哪一个.

最简单的选择是使用:

Func<string, string> moo = x => x.ToString();
Run Code Online (Sandbox Code Playgroud)

如果你真的想继续使用var,你可以这样做:

var moo = new Func<string, string>(x => x.ToString());
Run Code Online (Sandbox Code Playgroud)