[英]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.