【问题标题】:Make method that uses SQLiteConnection more reusable使使用 SQLiteConnection 的方法更可重用
【发布时间】:2021-01-13 01:02:13
【问题描述】:

我在我的项目中使用sqlite-net 并有一个名为 SqLiteHelper 的帮助程序类。在这个类中,我有一个简单的方法,它以列表的形式返回TableQuery 结果。 示例:

public static class SqLiteHelper
{
    public static List<Contact> GetTableQueryResults()
    {
        List<Contact> contacts;
        using (var connection = new SQLiteConnection(App.DatabasePath))
        {
            connection.CreateTable<Contact>();
            contacts = connection.Table<Contact>().ToList();
        }

        return contacts;
    }
}

我想让这个方法可重复使用,以便将来在其他上下文中使用它。例如,当我将有另一个具有不同类的项目时,然后是“联系”。我自己尝试过,将其重构为:

public static IList<T> GetTableQueryResults<T>()
{
    List<T> contacts;
    using (var connection = new SQLiteConnection(App.DatabasePath))
    {
        connection.CreateTable<T>();
        contacts = connection.Table<T>().ToList();
    }

    return contacts;
}

但是 SQLiteConnection.Table 方法会抛出以下错误:

有什么想法可以使这种方法可重复使用吗?
我看过here 但它与SQLite 无关。

【问题讨论】:

  • 数据库连接不应该被重用。在尽可能小的范围内创建、使用和处置它们。 DB Provider 实现了连接池来提高效率。里面有很多文档。
  • @ŇɏssaPøngjǣrdenlarp 数据库连接没有在这里重用..它是在 using 块中创建的,将被处理。我怀疑 OP 意味着您可以将泛型类型传递给的方法可重用。
  • @BrettCaswell 是的,这就是我想要实现的目标。看起来下面我的问题得到了使用 new constraint 的回答。

标签: c# sqlite generics


【解决方案1】:

在您的方法中提供T 的泛型类型约束为where T : new()new() 约束让编译器知道提供的任何类型参数都必须具有可访问的无参数构造函数。

方法:

public static IList<T> GetTableQueryResults<T>() where T : new()
{
    List<T> contacts;
    using (var connection = new SQLiteConnection(App.DatabasePath))
    {
        connection.CreateTable<T>();
        contacts = connection.Table<T>().ToList();
    }

    return contacts;
}

here 上了解new 约束。

【讨论】:

  • 感谢您的回复,看来我错过了 约束 主题。当我现在想使用该方法时,这种方法可以吗:contactsList = (List&lt;Contact&gt;) SqLiteHelper.GetTableQueryResults&lt;Contact&gt;();
  • 它将被标记为不必要的演员@Stan1k..你不需要转换为List&lt;Contact&gt;,由于在方法中指定Contact,它将返回一个List&lt;Contact&gt;类型。附带说明一下,该方法执行的操作不止一个,一个命令和查询(或 CreateTable 然后.Table&lt;T&gt;().ToList())...这种方法可以吗?...可能不是
  • @BrettCaswell 好的,我删除了演员表。拆分方法是我的下一个方法,谢谢提醒。
猜你喜欢
  • 2020-05-20
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 2018-12-14
  • 1970-01-01
相关资源
最近更新 更多