Skip to main content
 首页 » 编程设计

c#之使用 Action> 和 Func> 的命令

2024年02月13日17softidea

我正在处理 MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF并在命令部分遇到了障碍。具体来说,它创建一个基于 Action 和 Func 的命令。在我应该“构建并运行应用程序”的时候,我却遇到了编译错误。

命令内容:

public class Command : ICommand 
{ 
  private readonly Action<object> _execute; 
  private readonly Func<object, bool> _canExecute; 
  public Command(Action<object> execute, Func<object, bool> canExecute) 
  { 
    _execute = execute; 
    _canExecute = canExecute; 
  } 
 public void Execute(object parameter) 
  { 
    _execute(parameter); 
  } 
  public bool CanExecute(object parameter) 
  { 
    return (_canExecute == null) || _canExecute(parameter); 
  } 
  ... 
} 

方法调用内容:

private Command _showDetailsCommand; 
public Command ShowDetailsCommand 
{ 
  get  
  {  
      return _showDetailsCommand  
             ?? (_showDetailsCommand  
                = new Command(ShowCustomerDetails, IsCustomerSelected)); 
   } 
} 
public void ShowCustomerDetails() 
{ 
  if (!IsCustomerSelected()){ 
    throw new InvalidOperationException("Unable to display customer details. " 
                + "No customer selected."); 
  } 
  CustomerDetailsTabViewModel customerDetailsViewModel =  
            GetCustomerDetailsTab(SelectedCustomerID); 
  if (customerDetailsViewModel == null) 
  { 
    customerDetailsViewModel  
         = new CustomerDetailsTabViewModel 
               (_dataProvider,  
                SelectedCustomerID); 
    Tabs.Add(customerDetailsViewModel); 
  } 
  SetCurrentTab(customerDetailsViewModel); 
} 
private bool IsCustomerSelected() 
{ 
  return !string.IsNullOrEmpty(SelectedCustomerID); 
} 

我在 new Command(ShowCustomerDetails, IsCustomerSelected)) 下方有蓝色波浪线位带有“Northwind.Application.Command.Command(System.Action<object>, System.Func<object, bool>) 的最佳重载匹配项|”有一些无效的参数”。

当我尝试编译时,出现上述错误以及两条消息:

Argument 1: Cannot convert from method group to System.Action<object> 
Argument 2: Cannot convert from method group to System.Func<object, bool> 

现在,我对 Actions 和 Funcs 的了解比昨天多了,并且几乎可以通过将命令声明更改为以下方式来绕过错误:

private readonly Action _execute; 
private readonly Func<bool> _canExecute; 

并在整个代码中做类似的事情,但后来我得到一个错误,说我没有实现 ICommand

为了挽救我的额头/最近的墙,有人可以告诉我我做错了什么以便我可以修复它,或者给定的(书籍)代码让我出错,所以我可以继续前进。

请您参考如下方法:

那是因为

private bool IsCustomerSelected() 
{ 
    return !string.IsNullOrEmpty(SelectedCustomerID); 
} 

不是 Func<object, bool> 类型但是 Func<bool> .它应该看起来像

private bool IsCustomerSelected(object param) 
{ 
    return !string.IsNullOrEmpty(SelectedCustomerID); 
} 

你可以使用 Predicate<object>相反,至少对我来说,签名应该是什么样子更清楚。

关于c# - 使用 Action<> 和 Func<> 的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16186828/