简体   繁体   English

C#中的链接动作

[英]Chaining Actions in C#

I am trying to chain a bunch of functions calls into one callback function ptr (using Action) and each of those function calls take different arguments (so can't use delegates which would be ideal, unless I am missing something :)) So this is what I did: 我试图将一堆函数调用链接到一个回调函数ptr中(使用Action),并且每个函数调用都采用不同的参数(因此不能使用理想的委托,除非我遗漏了一些东西:))因此是我做的:

for (int i=0; i<num_func_calls; ++i)
{
    // could be anything different for each call
    int call_id = i;
    Action old_action = lastAction;
    lastAction = new Action(() =>
    {
        FuncCall(call_id, true);
        old_action();
    });
}

It works as I expect it to, but the question is: is this efficient/correct? 它按我的预期工作,但问题是:这样有效/正确吗? Are there any gotcha's or things I need to worry about with this? 是否有任何陷阱或需要为此担心的事情?

Thanks! 谢谢!

Here is an example using higher order functions. 这是使用高阶函数的示例。

static Action Apply(IEnumerable<int> data)
{
    Action zero = () => { };
    return data.Aggregate(zero, 
        (a, id) => a + (() => FuncCall(id, true)));
}

I'm not entirely sure what it is you're asking but I'm just going to address a couple of things in your post which are wrong. 我不确定您要问的是什么,但我只想解决您帖子中的几处错误。

Firstly; 首先; Action is a Delegate it's just one that accepts a single parameter and does not return a value. Action是一个Delegate它只是一个接受单个参数且不返回值的代表。 If I have some Action call it A - Delegate d = A; 如果我有一些Action称它为A Delegate d = A; will compile and run. 将编译并运行。

Secondly, to pass args in a general manner (meaning to some arbitrary function) you can use DynamicInvoke and wrap your arguments in an object array. 其次,要以一般方式传递args(意味着传递给任意函数),可以使用DynamicInvoke并将参数包装在对象数组中。 As long as the items in the array are of the right types and are in the right order the method will correctly execute. 只要数组中的项的类型正确且顺序正确,该方法即可正确执行。 Otherwise it will throw. 否则会抛出。

DynamicInvoke has a specific application but as an example if you provide me with an Object[] and a Delegate I can use DynamicInvoke to invoke the function without knowing what it's definition is. DynamicInvoke具有特定的应用程序,但作为示例,如果您为我提供Object[]Delegate ,则可以使用DynamicInvoke调用该函数而无需知道其定义是什么。 Like; 喜欢;

  myDelegate.DynamicInvoke(args); // where args is an Object[]

In general, you only want to use it when you're deciding which delegates to call at run time. 通常,仅在决定在运行时调用哪些代表时才要使用它。

This would be a great case to use a Task , since it has .ContinueWith which tells the task to run another task when it's complete. 使用Task会是一个很好的例子,因为它具有.ContinueWith ,它告诉任务在完成时运行另一个任务。 You can chain them together. 您可以将它们链接在一起。

http://msdn.microsoft.com/en-us/library/dd270696.aspx http://msdn.microsoft.com/en-us/library/dd270696.aspx

Also, you could reduce the delegate use by doing this: 另外,您可以通过执行以下操作减少委托的使用:

() => {
    for (int i=0; i<num_func_calls; ++i) FuncCall(i, true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM