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

旧时模样 提交于 2020-01-06 02:13:08

问题


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


回答1:


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());



回答2:


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

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



回答3:


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

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




回答4:


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();


来源:https://stackoverflow.com/questions/21169964/what-is-the-equivalent-c-sharp-code-for-a-vb-net-anonymous-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!