'Custom DelegateCommand: Action with parameters

I'd like that all the actions executed by a DelegateCommand would be logged. So I'd like to create a class (MyDelegateCommand) that would have to receive an Action as input: this Action can be

  • a method without parameters
  • a method with parameters
  • an async method without parameters
  • an async method with parameters

This is my implementation

public class MyDelegateCommand {

    private DelegateCommand _command;
    private Action _executeMethod;
    private Func<Task> _taskExecuteMethod;
    private BaseVM _baseVm;

    public MyDelegateCommand(BaseVM vm, Action executeMethod)  {
        _baseVm = vm;
        _executeMethod = executeMethod;
    }

    public MyDelegateCommand(BaseVM vm, Func<Task> taskExecuteMethod) {
        _baseVm = vm;
        _taskExecuteMethod = taskExecuteMethod;
    }

    public DelegateCommand GetCommand() {
        _command = new DelegateCommand(() => {
            Log.Information(_baseVm.GetType().Name + " ??????");
            _executeMethod();
        }, () => _baseVm.Modifica);

        return _command;
    }

    public DelegateCommand GetAsyncCommand() {
        _command = new DelegateCommand(async () => {
            Log.Information(_baseVm.GetType().Name + " ??????");

            await _taskExecuteMethod.Invoke();
        }, () => _baseVm.Modifica);

        return _command;
    }

}

I create my test methods

    public void customMethod1() {

    }

    public void customMethod2(string param1, string param2) {

    }

    public async Task customMethod1Async() {
        await ...
    }

    public async Task customMethod2Async(string param1, string param2) {
        await ...
    }

Commands creation

DelegateCommand d = new MyDelegateCommand(this, customMethod1).GetCommand();
DelegateCommand d = new MyDelegateCommand(this, customMethod1Async).GetAsyncCommand();

Now, my problem is how to do with methods with parameters. I read some solutions using Func<...> but I can't know in advance how many parameters my custom methods will request. I could think to add another parameters, such as

 object[] parameters

but... it's a nice solution? Any other ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source