内联委托声明(c#)

max*_*axp 32 c# delegates

我无法得到以下内容进行编译:

var x = new Action(delegate void(){});
Run Code Online (Sandbox Code Playgroud)

谁能指出我做错了什么?

Jon*_*eet 61

使用匿名方法时,不指定返回类型.这可行:

var x = new Action(delegate(){});
Run Code Online (Sandbox Code Playgroud)

一些替代品:

Action x = () => {}; // Assuming C# 3 or higher
Action x = delegate {};
Action x = delegate() {};
var x = (Action) (delegate{});
Run Code Online (Sandbox Code Playgroud)

  • @leppie:我也不喜欢,但这是使OP的代码编译所需的最小更改:)我将提供一些替代方案... (2认同)

Zot*_*tta 18

为什么不用lambda表示法?

Action myAction= (Action)(()=>
{
});
Run Code Online (Sandbox Code Playgroud)