Pass action delegate as parameter in C#

爱⌒轻易说出口 提交于 2019-12-22 08:40:14

问题


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*/});

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
}

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?


回答1:


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);
}

And call it like this:

ExpGenMethod((x, y) => {/*do something that makes sense*/});

When executing that delegate x evaluates to "Hi" and y to 1.




回答2:


(a,b) => {/*do something that matters*/} means that a and b are parameters which are going to be specified during the call. Here you are using constant so you should do something like () => { use "Hi"; use 1;} and that would get you back to your first working example.

If you want to pass parameter you cna do it this way:

public void work()
{
    ExpGenMethod((a) => {/*do something that matters*/});
}

public void ExpGenMethod(Action<int> inputDel, int parameterToUse)
{
    inputDel(parameterToUse);
}


来源:https://stackoverflow.com/questions/41869951/pass-action-delegate-as-parameter-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!