【问题标题】:Returning a function in C#在 C# 中返回一个函数
【发布时间】:2009-08-08 03:49:10
【问题描述】:

我有这个sn-p

private void westButton_click(object sender, EventArgs ea)
{
    PlayerCharacter.Go(Direction.West);
}

向北、南和东重复。

如何声明一个函数,让我以编程方式生成类似 ir 的方法?

例如,我想打电话

northButton.Click += GoMethod(Direction.North);

而不是定义方法,然后

northButton.Click += new EventHandler(northButton.Click);

【问题讨论】:

    标签: c# first-class


    【解决方案1】:
    northButton.Click += (s, e) => GoMethod(Direction.North);
    

    (或...)

    northButton.Click += (s, e) => PlayerCharacter.Go(Direction.North);
    

    【讨论】:

      【解决方案2】:

      我好像找到了解决办法:

      private EventHandler GoMethod(Direction dir)
      {
          return new EventHandler((object sender, EventArgs ea) => PlayerCharacter.Go(dir));
      }
      

      我唯一关心的是绑定时间;如果调用 GoMethod 时 PlayerCharacter 是 null,会发生什么?

      【讨论】:

      • PlayerCharacter 和 dir 变量用闭包捕获(关闭)。编译器将在后台生成额外的代码,以将它们“提升”到自己的私有类和实例中,以便它们在代码运行时保持其状态。
      【解决方案3】:
      northButton.Click += (s,e) => GoMethod(Direction.North);
      

      【讨论】:

      • () => PlayerCharacter.Go(Direction.North)
      • 如何将不带参数的 lambda 表达式添加到事件作为处理程序,该处理程序需要接受两个参数的委托:对象和 EventArgs?它应该是 (s,e) => PlayerCharacter.Go(Direction.North) 或委托 { PlayerCharacter.Go(Direction.North);}
      猜你喜欢
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多