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