我正在使用sqlite-net(
https://github.com/praeclarum/sqlite-net)在Android上使用Mono实现数据库并具有以下功能:
public class DatabaseTestASync { private sqliteAsyncConnection m_db; public delegate void StocksFound(List<Stock> list); public event StocksFound StocksFoundListener; // Uninteresting parts remove,e.g. constructor public void AddStock(Stock stock) { m_db.InsertAsync(stock).ContinueWith(t => { Debug.WriteLine(stock.Symbol + " added"); }); } public void GetAllStocks() { AsyncTableQuery<Stock> query = m_db.Table<Stock>().Where(stock => true); query.ToListAsync().ContinueWith(QueryReturns); } private void QueryReturns(Task<List<Stock>> t) { if (StocksFoundListener != null) StocksFoundListener(t.Result); }
这非常适合给我一个股票列表,但我设想在我的项目中有一个表集合,并且不想为每个表创建单独的AddX,GetAllX,QueryReturns(X)等.我正在执行这些数据库操作的通用方法并尝试以下方法:
public class DBQuery<T> { private sqliteAsyncConnection m_db; public delegate void OnRecordsFound(List<T> list); public event OnRecordsFound RecordsFoundListener; public DBQuery (sqliteAsyncConnection db) { m_db = db; } public void GetAllRecords() { AsyncTableQuery<T> query = m_db.Table<T>().Where(r => true); // COMPILE ERROR HERE query.ToListAsync().ContinueWith(QueryReturns); } private void QueryReturns(Task<List<T>> t) { if (RecordsFoundListener != null) RecordsFoundListener(t.Result); } }
但是,它没有编译说:’T’必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法’DatabaseUtility.AsyncTableQuery’中将其用作参数’T’.
关于如何让这种通用数据库访问工作的任何想法?
解决方法
我真的不知道sqlite内部,但这完全是关于泛型…
因为AsyncTableQuery是这样定义的
public class AsyncTableQuery<T> where T : new () {
public class DBQuery<T> where T : new ()
If you’re using a class or a method which has a
constrained generic
– you need to do the same on your method (or a class,
parameter
depending on where theT
is defined).