gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:25:20 25 4
gpt4 key购买 nike

我需要一些帮助来理解委托(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/

25 4 0