【问题标题】:Shorthand for initializing delegates初始化委托的简写
【发布时间】:2018-05-28 21:42:28
【问题描述】:

假设我有一个将委托作为参数的方法,如下所示:

public delegate void SampleDelegate(int foo);

public void DoSomething(SampleDelegate del) 
{
    //Does something
}

会有这样的简写吗?

static void Main(String[] args)
{
    void bar(int foo) {
        int x = foo;
    } 
    DoSomething(bar);
}

或者这是最有效的方法吗?

理想情况下,我会这样做:

static void Main(String[] args)
{
    DoSomething(void(int foo) {
        int x = foo;
    });
}

但这会产生语法错误。是否有正确的语法来执行上述操作?

【问题讨论】:

  • 您正在寻找匿名方法或 lambda。
  • @Tim_Schmelter 我展示的理想方法是不使用变量名 bar 并将内容简化为几行,从而使代码更简洁。
  • 你如何评价“最高效”?表现?字符?
  • @PatrickHofman 角色
  • 看起来这正是你想要的:stackoverflow.com/questions/2082615/…

标签: c# delegates shorthand


【解决方案1】:

您可以使用 lambda 表达式将函数创建为表达式:

DoSomething(myInt => { ... });

您也不需要声明SampleDelegate。您可以使用Action<int>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2013-08-03
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多