可以将具有相同主体的两个 Lambda 函数组合吗?

huangapple go评论60阅读模式
英文:

Is it possible to combine to lambdaas which have the same body?

问题

这两个 lambda 表达式是否可以合并,以避免重复维护相同的代码?

英文:
myEntry.Unfocused += async (s, e) =>
                {
                   // Same code
                }

myButton.Clicked += async (s, e) =>
                {
                   // Same code
                }

Is it possible to combine these tow lambdas in order to avoid maintaining the same code twice?

答案1

得分: 3

这些事件实际上是在调用时分配一个方法。只要签名匹配,您可以直接将其指向一个命名方法。

myEntry.Unfocused += OnEvent;
myButton.Clicked += OnEvent;

private async Task OnEvent(object sender, EventArgs args)
{
    // 在这里执行操作
}

只需确保返回类型正确。

英文:

These events are effectively assigning a method to call once invoked. As long as the signature matches, you can point it directly at a named method

myEntry.Unfocused += OnEvent;
myButton.Clicked += OnEvent;

private async Task OnEvent(object sender, EventArgs args)
{
    // Do stuff here
}

Just ensure the return type is correct.

huangapple
  • 本文由 发表于 2023年2月27日 01:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定