我将 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 sendretryAction
toMessageDialog
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/