如何使用参数执行动作委托列表

How to execute list of Action delegates with parameters

如何执行带参数的动作委托列表

  public static void CompareAll(List<Action<object,object>> compareDelegates)
    {
        List<Exception> exceptions = new List<Exception>();

      // The issue is in below line - how to pass parameters to the delegate
        compareDelegates.ForEach(del = (a,b) =>
        {
            try
            {
                del.Invoke(a,b);
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        });
    }

并从下面的代码中调用上面的函数

List<Action<object, object>> compareDelegates = new List<Action<object, object>>();

        compareDelegates.Add((a,b) => Compare(1,2));
        CompareAll(compareDelegates);

由于您的代表不会对传递给他们的输入执行任何操作,因此您应该使用空的 Action。将您的代码更改为:

public static void CompareAll(List<Action> compareDelegates)
{
    List<Exception> exceptions = new List<Exception>();

    compareDelegates.ForEach(del =>
    {
        try
        {
            del.Invoke();
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    });
}

// somewhere else...
List<Action> compareDelegates = new List<Action>();

compareDelegates.Add(() => Compare(1,2));
CompareAll(compareDelegates);

EDIT: Since your question is puzzling, but doesn't really make sense in the way I solved above, here's another take

如果您想要一个包含 Action<object,object> + 2 个值的列表,您应该像这样使用 Tuple 来做到这一点:

public static void CompareAll(
  List<Tuple<Action<Object,Object>,Object,Object>> compareDelegates)
{
    List<Exception> exceptions = new List<Exception>();

    compareDelegates.ForEach(tup =>
    {
        try
        {
            tup.Item1.Invoke(tup.Item2, tup.Item3);
        }
        catch (Exception ex)
        {
            exceptions.Add(ex);
        }
    });
}

// somewhere else...
List<Tuple<Action<Object,Object>,Object,Object>> compareDelegates = 
  new List<Tuple<Action<Object,Object>,Object,Object>>();

compareDelegates.Add(Tuple.Create((a,b) => Compare(a,b), 1, 2));
CompareAll(compareDelegates);

这一行:

compareDelegates.ForEach(del = (a,b) =>

你的参数很奇怪。在这种情况下 ForEach 的类型签名是 ForEach(Action<Action<object, object>>)。这是一个如何使用它的例子。

object parameter1 = 2;
object parameter2 = 3;
compareDelegates.ForEach(a => a(parameter1, parameter2));

这会用 23 调用列表中的每个操作。不过,您的示例并不是很清楚这到底意味着什么。