C# 中类似 JavaScript 的匿名函数

发布于 2024-07-30 17:41:29 字数 327 浏览 4 评论 0原文

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

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

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

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

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

Can the following be done in C#?:

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

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.

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

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

发布评论

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

评论(3

葬花如无物 2024-08-06 17:41:29
var greeting = "Hello" + new Func<String>(() => " World")() + "!";
var greeting = "Hello" + new Func<String>(() => " World")() + "!";
今天小雨转甜 2024-08-06 17:41:29

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

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

虽然有点难看,但确实有效。

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

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

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";
})};

It's slightly uglier, but it works.

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());
凉城 2024-08-06 17:41:29

我自己会写一个更详细的答案:

var tr = new TableRow { CssClass = "" };

tr.Cells.AddRange(new []
{
    new TableCell { CssClass = "", Text = "Hello" },
    new TableCell { CssClass = "", Text = new Func<String>(() => 
    {
        // logic goes here
        return "";
    })()}
});

Gonna put in a more verbose answer myself:

var tr = new TableRow { CssClass = "" };

tr.Cells.AddRange(new []
{
    new TableCell { CssClass = "", Text = "Hello" },
    new TableCell { CssClass = "", Text = new Func<String>(() => 
    {
        // logic goes here
        return "";
    })()}
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文