Action <T>和非参数方法

Joz*_*sky 2 c# generics delegates

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

void ShowWarningMessageDialog<T>(string infoMessage, Action<T> retryAction, T parameter);
Run Code Online (Sandbox Code Playgroud)

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

public void Authorize(object parameter = null)
Run Code Online (Sandbox Code Playgroud)

另一个选择是定义两个方法,如下所示,但我也不喜欢这样

void ShowWarningMessageDialog<T>(string infoMessage, Action<T> retryAction, T parameter);
void ShowWarningMessageDialog(string infoMessage, Action retryAction);
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*ert 7

关于你的评论:

两者都ShowWarningMessageDialog做同样的事情.如果用户retryAction需要MessageDialog,他们会发送给它.至于我,它闻起来有代码重复.

然后消除重复.我会写三个方法,像这样:

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. 
}
Run Code Online (Sandbox Code Playgroud)

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