使使用SQLiteConnection的方法更可重用

c#

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

任何想法如何使这种方法可重用?
我看过这里,但它与SQLite.

回答

在您的方法中提供Tas的泛型类型约束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在此处阅读约束。


以上是使使用SQLiteConnection的方法更可重用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>