c# - 执行带有参数的动态 Action 列表

标签 c# action

我正在根据其他一些数据构建一个操作列表。每个 Action 都应该调用一个方法,并且 Action 列表应该并行执行。我有以下代码,适用于无参数方法:

private void Execute() {

    List<Action> actions = new List<Action>();

    for (int i = 0; i < 5; i++) {
        actions.Add(new Action(DoSomething));
    }

    Parallel.Invoke(actions.ToArray());
}

private void DoSomething() {
    Console.WriteLine("Did something");
}

但是我怎样才能在方法有参数的情况下做类似的事情呢?以下不起作用:

private void Execute() {
    List<Action<int>> actions = new List<Action<int>>();

    for (int i = 0; i < 5; i++) {
        actions.Add(new Action(DoSomething(i))); // This fails because I can't input the value to the action like this
    }

    Parallel.Invoke(actions.ToArray()); // This also fails because Invoke() expects Action[], not Action<T>[]
}

private void DoSomething(int value) {
    Console.WriteLine("Did something #" + value);
}

最佳答案

只需保留您的 actions变量为 List<Action>而不是 List<Action<int>>两个问题都解决了:

private void Execute() {
    List<Action> actions = new List<Action>();

    for (int i = 0; i < 5; i++) {
        actions.Add(new Action(() => DoSomething(i)));         }

    Parallel.Invoke(actions.ToArray()); 
}

private void DoSomething(int value) {
    Console.WriteLine("Did something #" + value);
}

你想要的原因Action是因为您在调用操作时没有传递参数 - 您正在提供参数值作为委托(delegate)定义的一部分(请注意,委托(delegate)参数已更改到没有输入参数的 lambda - () => DoSomething(i) ),所以它是一个 Action ,不是 Action<int> .

关于c# - 执行带有参数的动态 Action 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882931/

相关文章:

c# - NHibernate - session 单例 C#

c# - 如何在 WPF 中创建带标题和排序的多列 TreeView?

c# - 如何在 MongoDB 中使用小数类型

c# - 如何从 MethodInfo 创建 Action 委托(delegate)?

javascript - 当字段改变时捕获事件

c# - Dapper with .NET Core - 注入(inject)的 SqlConnection 生命周期/范围

c# - 标签文本值未设置

java - 导出 Excel 并防止用户重新处理操作直至完成的操作方法

java - 无法从 oozie.action.conf.xml 检索属性

swift - 处理两种文档类型