简体   繁体   English

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

[英]What is the equivalent C# code for a VB.NET anonymous delegate?

What is the equivalent C# code for the following VB.NET: 以下VB.NET的等效C#代码是什么:

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

I thought that this should work: 我认为这应该可行:

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

but that yielded a compiler error: Cannot assign lamda expression to an implicitly-typed local variable 但这产生了编译器错误: Cannot assign lamda expression to an implicitly-typed local variable

After some further investigation, I discovered that the type of the variable moo ( moo.GetType() ) in the VB example is VB$AnonymousDelegate_0'2[System.String,System.String] 经过进一步调查,我发现VB示例中的变量moomoo.GetType() )的类型为VB$AnonymousDelegate_0'2[System.String,System.String]

Is there anything equivalent to this in C#? C#中有与此等效的东西吗?

The lambda needs to infer the type of the delegate used from its context. lambda需要从其上下文中推断使用的委托的类型。 An implicitly typed variable will infer its type from what is assigned to it. 隐式类型的变量将从分配给它的内容中推断出其类型。 They are each trying to infer their type from the other. 他们每个人都试图从另一个人推断自己的类型。 You need to explicitly use the type somewhere . 您需要在某处显式使用该类型。

There are lots of delegates that can have the signature that you're using. 有很多代表可以使用您正在使用的签名。 The compiler needs some way of knowing which one to use. 编译器需要某种方式来知道要使用哪个。

The easiest option is to use: 最简单的选择是使用:

Func<string, string> moo = x => x.ToString();

If you really want to still use var , you can do something like this: 如果你真的想仍然使用var ,你可以这样做:

var moo = new Func<string, string>(x => x.ToString());

您无需在lambda表达式中指定参数类型,只需执行以下操作:

Func<string, string> moo = (x) => x.ToString();
Func<string, string> moo = (x) => x.ToString();

使用var C#并不知道您是否需要Func and Action或其他功能。

The problem is that you can't use implicit typing for delegates. 问题是您不能对代理使用隐式类型。 Meaning the var on the LHS is the actual cause of the issue, your lambda expression is fine. 意味着LHS上的var是问题的实际原因,您的lambda表达式很好。 If you change it to the following it will compile and work as expected; 如果将其更改为以下内容,它将按预期进行编译和运行;

 Func<string, string> moo = (string x) => x.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM