What is the equivalent C# code for a VB.NET anonym

2019-08-07 05:20发布

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#?

4条回答
神经病院院长
2楼-- · 2019-08-07 05:32

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());
查看更多
戒情不戒烟
3楼-- · 2019-08-07 05:33

You don't need to specify parameter type in lambda expressions, just do the following:

Func<string, string> moo = (x) => x.ToString();
查看更多
啃猪蹄的小仙女
4楼-- · 2019-08-07 05:44

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();
查看更多
可以哭但决不认输i
5楼-- · 2019-08-07 05:47
Func<string, string> moo = (x) => x.ToString();

With var C# doesn't know if you want a Func and Action or something else.

查看更多
登录 后发表回答