标题很拗口,甚至不知道它的准确的(不能做的多大意义这个),所以我会尽力解释想我做到在C#使用等效javascript.关于我应该对这个问题提出什么标题的任何建议都非常受欢迎.
在C#,说我已经定义了这个功能:
Func<string, string> getKey = entity => {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
};
string key = getKey(/* "a", "b", or something else */);
Run Code Online (Sandbox Code Playgroud)
现在假设我不想getKey显式定义函数,而是像在此等效javascript代码段中那样匿名使用它:
string key = (function(entity) {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
}(/* "a", "b", or something else */));
Run Code Online (Sandbox Code Playgroud)
我该C#怎么写呢?我试过了:
string key = (entity => {
switch(entity) {
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
})(/* "a", "b", or something else */);
Run Code Online (Sandbox Code Playgroud)
但我得到语法错误CS0149: Method name expected.
在此先感谢,欢呼.
IMO,最接近的是这个:
var key = new Func<string, string>(entity =>
{
switch (entity)
{
case "a":
return "foo";
case "b":
return "bar";
default:
return "baz";
}
})("a");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |