传递具有不同数量和类型参数的函数

时间:2016-09-09 02:15:26

标签: c# asp.net .net c#-4.0

我有很多看起来像这样的函数:

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以选择性地接受其他参数?

3 个答案:

答案 0 :(得分:1)

也许这就是:

public void RunThing(Action action, RecurringTaskRunResult result) {
    try {
        action();
    }
    catch (Exception e) {
        result.Succeeded = false;
        result.Results += e.ToString();
        db.SaveChanges();
    }
}

RunThing(() => DoParticularThing(result), result);
RunThing(() => DoSomethingElse(result, list), result);

答案 1 :(得分:0)

您可以使用参数接受函数中的所有参数。

public void RunThing(Action<RecurringTaskRunResult> action, RecurringTaskRunResult result, params object[] list) {
    try {
        action(result);
        foreach(var item in list)
        {
            // Do action with your additional parameter
        }
    }
    catch (Exception e) {
        result.Succeeded = false;
        result.Results += e.ToString();
        db.SaveChanges();
    }
}

答案 2 :(得分:0)

在所有情况下,您希望RunThing能够访问RecurringTaskRunResult,以便您可以在其上设置一些字段,但不需要访问任何其他参数。你可以尝试这样的事情:

void Action1(RecurringTaskRunResult result) { }
void Action2(RecurringTaskRunResult result, object foo) { }

RecurringTaskRunResult result = ...;
object foo = ...;
RunThing(Action1, result);
RunThing(res => Action2(res, foo), result);