有没有办法直接使用 C# 方法作为委托?
这更多的是一个 C# 语法问题,而不是一个需要解决的实际问题。假设我有一个采用委托作为参数的方法。假设我定义了以下方法:
void TakeSomeDelegates(Action<int> action, Func<float, Foo, Bar, string> func)
{
// Do something exciting
}
void FirstAction(int arg) { /* something */ }
string SecondFunc(float one, Foo two, Bar three){ /* etc */ }
现在,如果我想以 FirstAction
和 SecondFunc
作为参数调用 TakeSomeDelegates
,据我所知,我需要做这样的事情:
TakeSomeDelegates(x => FirstAction(x), (x,y,z) => SecondFunc(x,y,z));
但是有没有更方便的方法来使用适合所需委托签名的方法而无需编写 lambda?理想情况下类似于 TakeSomeDelegates(FirstAction, SecondFunc)
,尽管显然这不能编译。
This is more of a C# syntax question rather than an actual problem that needs solving. Say I have a method that takes a delegate as parameter. Let's say I have the following methods defined:
void TakeSomeDelegates(Action<int> action, Func<float, Foo, Bar, string> func)
{
// Do something exciting
}
void FirstAction(int arg) { /* something */ }
string SecondFunc(float one, Foo two, Bar three){ /* etc */ }
Now if I want to call TakeSomeDelegates
with FirstAction
and SecondFunc
as arguments, As far as I can tell, I need to do something like this:
TakeSomeDelegates(x => FirstAction(x), (x,y,z) => SecondFunc(x,y,z));
But is there a more convenient way to use a method that fits the required delegate signature without writing a lambda? Ideally something like TakeSomeDelegates(FirstAction, SecondFunc)
, although obviously that doesn't compile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在寻找的是一种名为“方法组”的东西。有了这些,你可以替换一行 lamdas,例如:
was:
替换为方法组后:
What you're looking for is something called 'method groups'. With these, you can replace one line lamdas, such as:
was:
after replacing with method groups:
只需跳过函数名称上的括号即可。
编辑:
仅供参考,因为括号在 VB 中是可选的,所以他们必须写这个......
Just skip the parens on the function names.
EDIT:
FYI Since parens are optional in VB, they have to write this...
编译器会接受需要委托的方法组的名称,只要它能够确定选择哪个重载,就不需要构建 lambda。您看到的确切编译器错误消息是什么?
The compiler will accept names of method groups where a delegate is needed, as long as it can figure out which overload to choose, you don't need to build a lambda. What is the exact compiler error message you're seeing?
是的,它被称为方法组,更准确的例子是......
通过这种方式,您可以使用方法组。
Yes it is called Method Group, and more precise example of that is...
In this way you can use Method Group.