RelayCommand 和委托,试图理解委托

RelayCommand and delegates, trying to understand delegates

我需要一些帮助来了解委托是什么,以及我是否在我的程序中使用过它。我正在使用我在另一个堆栈 post 中找到的 RelayCommand class 来实现我的命令。

中继命令:

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Func<bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<bool> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));

        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute.Invoke();
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

在我的 ViewModel 的构造函数中,我这样做:

 public ICommand SearchCommand { get; set; }

 //Constructor
 public BookingViewModel()
 {
     SearchCommand = new RelayCommand(SearchCommand_DoWork, () => true);     
 }

 public async void SearchCommand_DoWork(object obj)
 {
  //Code inside this method not shown
 }

我知道委托是一种封装方法的类型。你可以这样写一个委托:

public delegate int MethodName(string name)

其中委托封装了 return 类型为 int 并采用字符串参数的方法 MethodName。

这是否意味着在使用代码中所示的 ICommand 时创建了一个委托?其中封装方式为"SearchCommand_DoWork"

希望有人能帮我解决一些问题。

Does this mean that there is a delegate created when using ICommand like i shown in the code? Where the encapsulating method is "SearchCommand_DoWork"

您正在创建 RelayCommand 类型的新对象。正如您在 class' 构造函数中看到的那样,您正在传递一个 Action 对象(委托 returns 没有值)和一个 Func 对象(委托 returns 一个值)。

对于 Action 委托,您要传递一个封装了无效函数 SearchCommandDoWork 的对象,对于 Func 对象,您要传递一个不带参数且始终 returns 为真的 lambda 函数。

Action 委托封装了您的 SearchCommand_DoWork 函数(委托基本上是一个类型安全的函数指针)。

Action 和 Func 都是预定义的委托。您还可以定义自己的委托,这就是

public delegate int MethodName(string name)

会。