Command Pattern : How to pass parameters to a command?

前端 未结 13 1084
夕颜
夕颜 2020-12-07 16:43

My question is related to the command pattern, where we have the following abstraction (C# code) :

public interface ICommand
{
    void Execute();
}
<         


        
13条回答
  •  渐次进展
    2020-12-07 17:08

    Based on the pattern in C#/WPF the ICommand Interface (System.Windows.Input.ICommand) is defined to take an object as a parameter on the Execute, as well as the CanExecute method.

    interface ICommand
                {
                    bool CanExecute(object parameter);
                    void Execute(object parameter);
                }
    

    This allows you to define your command as a static public field which is an instance of your custom command object that implements ICommand.

    public static ICommand DeleteCommand = new DeleteCommandInstance();
    

    In this way the relevant object, in your case a person, is passed in when execute is called. The Execute method can then cast the object and call the Delete() method.

    public void Execute(object parameter)
                {
                    person target = (person)parameter;
                    target.Delete();
                } 
    

提交回复
热议问题