gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:25:37 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com