简体   繁体   English

在C#中返回函数

[英]Returning a function in C#

I have this snippet 我有这个片段

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

repeated for North, South and East. 对北部,南部和东部重复。

How can I declare a function that'd let me generate methods like ir programmatically? 如何声明一个可以让我以编程方式生成方法的函数?

eg, I'd like to be able to call 例如,我想可以打电话

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

instead of defining the method, and then 而不是定义方法,然后

northButton.Click += new EventHandler(northButton.Click);
northButton.Click += (s, e) => GoMethod(Direction.North);

(要么...)

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

I seem to have found a solution: 我似乎找到了解决方案:

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

My only concern would be about binding time; 我唯一关心的是绑定时间。 if PlayerCharacter is null when I call GoMethod, what would happen? 如果在我调用GoMethod时PlayerCharacter为null ,会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM