将动作委托作为C#中的参数传递 [英] Pass action delegate as parameter in C#
问题描述
我有一个接受 Action
委托并执行给定方法的方法,如下所示:
I have a method which accepts an Action
delegate and executes the given method as shown here:
public void ExpMethod(Action inputDel)
{
inpuDel();
}
我可以像上面这样调用给定方法:
I can call above given method like this:
ExpMethod(() => {/*do something that matters*/});
一切正常。到现在为止还挺好。现在,我想拥有一个将通用 Action
委托作为输入参数的方法-像这样:
Everything works fine. So far so good. Now I want to have a method which takes a generic Action
delegate as an input parameter - like this:
public void ExpGenMethod(Action<string,int> inputDel)
{
// I don't know how to call the supplied delegate as it requires parameters
}
此外,我正试图将此称为 ExpGenMethod
这样:
Also, I am trying to call this ExpGenMethod
in this way:
ExpGenMethod(("Hi",1) => {/*do something that makes sense*/});
但是它显示语法错误。请让我知道在这种情况下如何使用通用动作委托?
But it shows syntax errors. Please let me know how to use generic action delegate in this case?
推荐答案
委托的全部目的是要有一个指针一种方法。因此,在声明它时将参数传递给它是没有意义的。而是在执行委托的方法中传递委托的参数,在您的情况下,在 ExpGenMethod
中:
The whole point of a delegate is to have a pointer to a method. Passing parameters to it while it´s being declared is therefor pointless. Instead pass the arguments for your delegate within the method that executes the delegate, in your case within ExpGenMethod
:
您应改为执行以下操作:
You should do this instead:
public void ExpGenMethod(Action<string,int> inputDel)
{
inputDel("Hi", 1);
}
并这样称呼它:
ExpGenMethod((x, y) => {/*do something that makes sense*/});
执行该委托时, x
计算为嗨
和 y
到 1
。
When executing that delegate x
evaluates to "Hi"
and y
to 1
.
这篇关于将动作委托作为C#中的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!