繁体   English   中英

使使用 SQLiteConnection 的方法更可重用

[英]Make method that uses SQLiteConnection more reusable

我在我的项目中使用sqlite-net并且有一个名为 SqLiteHelper 的助手 class。 在这个 class 里面,我有一个简单的方法,可以将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;
    }
}

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

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<> 方法会抛出以下错误:

有什么想法可以使这种方法可重用吗?
我在这里看了一下,但它与SQLite

在您的方法中提供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;
}

此处阅读有关new约束的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM