C# 中类似 JavaScript 的匿名函数
可以在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用匿名类型,则必须显式转换匿名方法或 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:
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:
我自己会写一个更详细的答案:
Gonna put in a more verbose answer myself: