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

编程入门 行业动态 更新时间:2024-10-22 21:22:05
本文介绍了什么是VB.NET匿名委托的等效C#代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下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#代码?

本文发布于:2023-11-12 20:30:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582461.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   VB   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!