C# 中类似 JavaScript 的匿名函数 [英] JavaScript-like anonymous functions in C#

查看:23
本文介绍了C# 中类似 JavaScript 的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在 C# 中完成以下操作吗?:

Can the following be done in C#?:

var greeting = "Hello" + function ()
{
    return " World";
}() + "!";

我想做一些类似的事情(C# 伪代码):

I want to do something along the lines of this (C# pseudo code):

var cell = new TableCell { CssClass = "", Text = return delegate ()
{
     return "logic goes here";
}};

基本上我想实现一些逻辑的内联作用域,而不是将该块逻辑移动到一个单独的方法中.

Basically I want to implement in-line scoping of some logic, instead of moving that chunk logic into a separate method.

推荐答案

如果您使用的是匿名类型,那么您必须显式地强制转换匿名方法或 lambda 表达式;如果您要分配给类型已知的属性,则不会.例如:

If you're using an anonymous type then you'll have to cast the anonymous method or lambda expression explicitly; if you're assigning to a property where the type is already known, you won't. For example:

var cell = new TableCell { CssClass = "", Text = (Func<string>) (() =>
{
     return "logic goes here";
})};

它有点丑,但它有效.

但是是的,您当然可以使用这样的匿名函数.当您想要检索文本时,您需要明确调用它,请注意:

But yes, you can certainly use an anonymous function like this. You'll need to explicitly call it when you want to retrieve the text, mind you:

Console.WriteLine("{0}: {1}", cell.CssClass, cell.Text());

这篇关于C# 中类似 JavaScript 的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆