一个好看的代码问题(与将方法作为参数传递有关)

A matter of good looking code (related to passing methods as a parameter)

我一直在阅读 C# 中的委托和传递方法作为参数,只是因为我的 "OCD" 在看这段代码时让我很头疼:

 public static T GetSingleItem<T>(string query, params object[] args) where T : new()
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        return db.Query<T>(query, args).FirstOrDefault();
    }
}

public static List<T> GetItems<T>(string query, params object[] args) where T : new()
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        return db.Query<T>(query, args);
    }
}

public static void Insert(object obj)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        db.Insert(obj);
    }
}

public static void Update(object obj)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        db.Update(obj);
   }
}

有没有办法将 using 语句和 db.Trace 封装在一个方法中,然后简单地调用方法内容的其余部分,例如db.Update(obj) 来自他们的特定方法?

将分部方法作为参数传递的明显问题,例如

public static T Runner<T>(Func<T> funcToRun)

是不是我正在从 using 语句实例化的对象中调用 db.Update()。

对此模式有什么巧妙的解决方案吗?

我并不是说这是重构它的最佳方式,但你的想法几乎就在那里,我只是扩展了它。

我相信,但我不确定,这可能被称为模板方法模式(但我找到的示例不使用 Func,它们使用虚方法和派生的 类, 但概念是一样的).

你需要一个作空:

public static void RunAction(Action<SQLiteConnection> actionToRun)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        actionToRun(db);
   }
}

还有一个用于 return 类型:

public static T RunFunc<T>(Func<SQLiteConnection, T> funcToRun) where T : new()
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        return funcToRun(db);
   }
}

调用无效Action:

public static void Update(object obj)
{
    RunAction(db => db.Update(obj));
}

正在调用 returning Func:

public static List<T> GetItems<T>(string query, params object[] args) where T : new()
{
    return RunFunc<List<T>>(db => db.Query<T>(query, args));
}