以下VB.NET的等效C#代码是什么:
What is the equivalent C# code for the following VB.NET:
Dim moo = Function(x as String)x.ToString( )
我以为这应该有效:
var moo =(string x)=> x.ToString();
但是会产生编译器错误:无法将lamda表达式分配给隐式类型本地变量
but that yielded a compiler error: Cannot assign lamda expression to an implicitly-typed local variable
经过进一步的调查,我发现变量的类型 moo moo.GetType())是$ code> VB $ AnonymousDelegate_0'2 [System.String,System.String]
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]
在C#中有什么相当于这个吗?
Is there anything equivalent to this in C#?
推荐答案p> lambda需要推断从其上下文中使用的委托的类型。一个隐式类型的变量将根据分配给它的类型来推断它的类型。他们都试图从另一个推断他们的类型。您需要明确使用 中的类型。
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.
最简单的选项是使用:
Func<string, string> moo = x => x.ToString();如果您真的想使用 var ,你可以这样做:
If you really want to still use var, you can do something like this:
var moo = new Func<string, string>(x => x.ToString());更多推荐
什么是VB.NET匿名委托的等效C#代码?
发布评论