返回 C# 中的函数

发布于 2024-07-30 01:21:36 字数 395 浏览 3 评论 0原文

这个片段

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

我为北、南和东重复了

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

例如,我希望能够调用

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

而不是定义方法,然后

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

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?

e.g., 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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁与争疯 2024-08-06 01:21:36
northButton.Click += (s, e) => GoMethod(Direction.North);

(或者...)

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

(or...)

northButton.Click += (s, e) => PlayerCharacter.Go(Direction.North);
逆光飞翔i 2024-08-06 01:21:36

我似乎找到了解决方案:

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

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

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?

捂风挽笑 2024-08-06 01:21:36
northButton.Click += (s,e) => GoMethod(Direction.North);
northButton.Click += (s,e) => GoMethod(Direction.North);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文