c# - 使使用 SQLiteConnection 的方法更加可重用

标签 c# sqlite generics

我在我的项目中使用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无关。

最佳答案

在您的方法中提供 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 了解约束.

关于c# - 使使用 SQLiteConnection 的方法更加可重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65688417/

相关文章:

java - 在类中定义的方法在泛型类 (Java) 中找不到

c# - 四舍五入到最接近的五

c# - 发送附件时无法访问已关闭的流

sqlite - SQLite 有游标吗?

c# - 从 C# 连接和使用 sqlite 数据库的最佳方法是什么

java - 传入不同的容器类型

c# - 如何让服务器应用程序使用单独的核心

c# - Serilog 电子邮件接收器 : single email at end of application

sql - 使CASE-WHEN-子句发出一个元组

Java - 来自父级的相同方法,但使用每个子级的单独属性