英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论