【发布时间】:2016-09-09 02:15:25
【问题描述】:
我有很多这样的函数:
public void DoParticularThing(RecurringTaskRunResult result) {
try {
// Do a bunch of stuff
}
catch (Exception e) {
result.Succeeded = false;
result.Results += e.ToString();
db.SaveChanges();
}
}
所以我决定以 DRY 代码的名义把这个提取出来:
public void RunThing(Action<RecurringTaskRunResult> action, RecurringTaskRunResult result) {
try {
action(result);
}
catch (Exception e) {
result.Succeeded = false;
result.Results += e.ToString();
db.SaveChanges();
}
}
这样我可以像这样调用DoParticularThing:
RunThing(DoParticularThing, result);
但我的一些函数也接受另一个参数:
public void DoOtherParticularThing(RecurringTaskRunResult result, List<string> strings) {
try {
// Do a bunch of stuff
}
catch (Exception e) {
result.Succeeded = false;
result.Results += e.ToString();
db.SaveChanges();
}
}
如何修改RunThing 以选择性地接受另一个参数?
【问题讨论】:
-
添加重载。干燥剂。或干燥但不要过火。
-
@EdPlunkett 这就是我现在正在做的事情,但这似乎是朝另一个方向迈出的一步:p
-
好吧,你可以编写一个方法,在 try/catch 中调用任意 Action。