c# - Action<T> 和非参数方法

标签 c# generics delegates

我将 Action 用于稍后在另一个模块中调用的重试操作方法。使用此 Action 的方法签名如下

void ShowWarningMessageDialog<T>(string infoMessage, Action<T> retryAction, T parameter);

在某些情况下,我需要发送不带参数的重试方法,当然这是不可能的。我尝试了一些像这样丑陋的解决方案(参数只是假的,没有在方法中使用)

public void Authorize(object parameter = null)

另一种选择是像下面这样定义两个方法,但我也不喜欢这样

void ShowWarningMessageDialog<T>(string infoMessage, Action<T> retryAction, T parameter);
void ShowWarningMessageDialog(string infoMessage, Action retryAction);

你有一些模式或建议如何处理它吗?

最佳答案

关于您的评论:

both of ShowWarningMessageDialog do the same. They send retryAction to MessageDialog that calls it if user wants. As for me, it smells with code duplication.

然后消除重复。我会编写三种方法,如下所示:

void ShowWarningMessageDialog<T>(
    string infoMessage, 
    Action<T> retryAction, 
    T parameter)
{
    // Do no work here; defer to other method.
    ShowWarningMessageDialog(infoMessage, ()=>{retryAction(parameter);});
}
void ShowWarningMessageDialog<T>(
    string infoMessage, 
    Action<T> retryAction)
{
    // Do no work here; defer to other method.
    ShowWarningMessageDialog(infoMessage, retryAction, default(T));
}
void ShowWarningMessageDialog(
    string infoMessage, 
    Action retryAction)
{
    // Actually do the work here. 
}

现在您拥有了可能需要的所有签名,而实际代码只在一个地方。

关于c# - Action<T> 和非参数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121875/

相关文章:

ios - 将 nil 传递给具有泛型类型约束的可选参数的编译错误

c# - 为什么有时 DateTime.TryParse 工作而其他时间只有 DateTime.ParseExact 工作?

c# - Windows窗体打开其他窗体

c# - 如何播放双重数组(包括波浪)

java - 无界通配符类型和有界通配符类型之间的区别?

由方法上下文定义的 Swift 泛型类型

c# - 能否从某种方法名称集合创建 C# 4.0 中的多播委托(delegate)?

ios - 具有多个 Controller 的单个委托(delegate)

c# - Delegate.BeginInvoke()/EndInvoke() 实现

c# - 如何在 C# 中使用模板/格式从标签打印机打印标签