c# - RelayCommand 和委托(delegate),尝试理解委托(delegate)

标签 c# delegates icommand

我需要一些帮助来理解委托(delegate)是什么,以及我是否在我的程序中使用了它。我正在使用在另一篇堆栈文章中找到的 RelayCommand 类来实现我的命令。

中继命令:

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
 }

我知道委托(delegate)是一种封装方法的类型。您可以像这样编写委托(delegate):

public delegate int MethodName(string name)

委托(delegate)封装了 MethodName 方法,该方法的返回类型为 int,并采用字符串参数。

这是否意味着像代码中所示使用 ICommand 时创建了一个委托(delegate)?其中封装方法为“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 类型的新对象。正如您在类的构造函数中看到的,您传入了一个 Action 对象(不返回值的委托(delegate))和一个 Func 对象(返回值的委托(delegate))。

对于 Action 委托(delegate),您传入一个封装 void 函数 SearchCommandDoWork 的对象,对于 Func 对象,您传入一个不带参数且始终返回 true 的 lambda 函数。

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

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

public delegate int MethodName(string name)

是的。

关于c# - RelayCommand 和委托(delegate),尝试理解委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328812/

相关文章:

c# - 为什么委托(delegate)不处理事件 null

c# - 从命令操作中更新 UI 元素

c# - Owin Authentication.SignIn 不工作

c# - NHibernate 左外连接名称到地址

ios - Socket Rocket 异步委托(delegate)方法

c# - 将命令参数传递给 WPF 中 ViewModel 中的方法?

c# - WPF:如果 TextBox 中的文本发生更改,则更新按钮

c# - 带有 v4 Webchat channel 的 Bot 框架问候消息

c# - 在 C# 中为游戏创建自定义消息框

c# - 获取委托(delegate)的具体返回类型