简体   繁体   中英

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

What is the equivalent C# code for the following VB.NET:

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

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]

Is there anything equivalent to this in C#?

The lambda needs to infer the type of the delegate used from its context. 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 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. If you change it to the following it will compile and work as expected;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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