如果您是一名语言设计师,您将如何使 lambda 忽略参数更加简洁?

发布于 2024-07-26 01:19:59 字数 713 浏览 3 评论 0原文

基于这个,如何使忽略参数更加简洁?

var m = menuStrip.Items.Add("Hello", null, delegate { MessageBox.Show("Como Esta Mundo"); });

我正在思考:

var m = menuStrip.Items.Add("Hello", null, ==> MessageBox.Show("Como Esta Mundo") );

var m = menuStrip.Items.Add("Hello", null, ? => MessageBox.Show("Como Esta Mundo") );

或者可能是这样:

var m = menuStrip.Items.Add("Hello", null, ?=> MessageBox.Show("Como Esta Mundo") );

你会怎么看?

<语言演化观察> 他们甚至添加?? 运算符到语言中,这确实很漂亮。 现在我想如果他们想与之相反(即NullIf运算符),如果你想将某些东西视为相同的“”或零等于null,这是非常有用的。

Based on this, how would you make ignoring parameters more succint?

var m = menuStrip.Items.Add("Hello", null, delegate { MessageBox.Show("Como Esta Mundo"); });

I'm thinking along the lines of:

var m = menuStrip.Items.Add("Hello", null, ==> MessageBox.Show("Como Esta Mundo") );

var m = menuStrip.Items.Add("Hello", null, ? => MessageBox.Show("Como Esta Mundo") );

or perhaps this:

var m = menuStrip.Items.Add("Hello", null, ?=> MessageBox.Show("Como Esta Mundo") );

What would be your take?

<language evolution observation>
They even add ?? operator to the language, which is indeed beautiful. Now I think if they would like to make a converse of it (i.e. NullIf operator), this is very useful if you want to treat something as the same "" or zero is equal to null </language evolution observation>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总攻大人 2024-08-02 01:19:59

好吧,就像匿名方法一样,您必须知道尝试将 lambda 表达式转换为的编译时类型(除非 C# 开始支持自由函数,这是一个更大的变化)。

我很喜欢?=> 不过:

Action<int> foo = ?=> Console.WriteLine("Okay");
EventHandler handler = ?=> Console.WriteLine("Okay too");

现在,由于 ToolStripCollection.Add 专门将 EventHandler 声明为委托,因此您的示例就可以了。 但事实并非如此:

control.Invoke(?=> Console.WriteLine("No no no"));

这里编译器不知道尝试将 lambda 表达式转换为哪种类型,因此需要进行强制转换 - 就像今天的匿名方法一样。

Well, just like anonymous methods, you'd have to know the compile-time type you were trying to convert the lambda expression to (unless C# starts supporting free functions, which is a bigger change).

I quite like ?=> though:

Action<int> foo = ?=> Console.WriteLine("Okay");
EventHandler handler = ?=> Console.WriteLine("Okay too");

Now as ToolStripCollection.Add specifically declares EventHandler as the delegate, your examples would be okay. This wouldn't though:

control.Invoke(?=> Console.WriteLine("No no no"));

Here the compiler wouldn't know which type to try to convert the lambda expression to, so it would require a cast - just like anonymous methods do today.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文