user12445601
user12445601

Reputation:

Execute a list of methods passed as parameter of a function

I would like to achieve such a following function:

public void MyMethod<T>(params Func<T[], void>[] funcs)
{
   foreach (var func in funcs)
   {
      func();
   }
}

public void Print1<T>(params T[] objs)
{
   Console.WriteLine("==== I am in 1 ====");
}

public void Print2<T>(params T[] objs)
{
   Console.WriteLine("==== I am in 2 ====");
}

static void Main()
{
   MyMethod(
      Print1(1, 2, 3),
      Print2("1", "2", "3"),
   );
}

expecting to execute outputting:

==== I am in 1 ====
==== I am in 2 ====

What i managed so far is this:

public void MyMethod2(params Action<object>[] funcs)
{
   foreach (var func in funcs)
   {
      Execute(func);
    }
 }

 public Action<object> Print1<T>(params T[] objs)
 {
     PrintLog("==== I am in 1 ====");
     return null;
 }

 public Action<object> Print2<T>(params T[] objs)
 {
     PrintLog("==== I am in 2 ====");
     return null;
 }

 public class MyDelegateCommand : ICommand
 {
    public MyDelegateCommand(Action<object> executeAction) => _executeAction = executeAction;
    private readonly Action<object> _executeAction;
    public void Execute(object parameter) => _executeAction?.Invoke(parameter);
 }

but the problem is that I get printed twice, like this:

==== I am in 1 ====
==== I am in 2 ====
==== I am in 1 ====
==== I am in 2 ====

I think the reason in this second approach is because the object of the Actioon<object> not being passed/returned, but i anyway ask me if it wouldn't be better to manage it with the first approach i am requesting. Any idea how could I solve this issue?

Thanks in advance for any help!

Upvotes: 1

Views: 281

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064134

It looks like you want:

public static void MyMethod(params Action[] funcs)
{
   foreach (var func in funcs)
   {
      func();
   }
}

public static void Print1<T>(params T[] objs)
{
   Console.WriteLine("==== I am in 1 ====");
}

public static void Print2<T>(params T[] objs)
{
   Console.WriteLine("==== I am in 2 ====");
}

static void Main()
{
   MyMethod(
      () => Print1(1, 2, 3),
      () => Print2("1", "2", "3")
   );
}

In particular: the <T> is not common between the two calls, so it cant be generic on MyMethod; fine in Print1<T> and Print2<T> though, as the respective <T> is specified (implied) in the lambda.

Upvotes: 2

Related Questions