0

我正在尝试编写一个通用方法来从表中获取数据。

我正在使用 sqlite-net ORM。

我的方法编译好删除:

public bool DeleteItem<T>(T NewItem)
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    var result = conn.Delete<T>(NewItem);

    //...
}

public void CreateTable<T>()
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    conn.CreateTable<T>();
    conn.Close();
}

但是,如果我尝试将表格数据作为列表获取,则会在 conn.Table 处收到编译错误:

T 必须是非抽象类型 ....

这是我不想编译的代码:

public List<T> GetAllItems<T>(string SelTable)
{
    SQLiteConnection conn = new SQLiteConnection(GetConnection());
    List<T> MyItems = conn.Table<T>().ToList();
    conn.Close();
    return MyItems;
}
4

1 回答 1

1

SQLiteConnection 中 Table 的定义是

public TableQuery<T> Table<T>() where T : new();

所以你必须添加类型约束:

public bool DeleteItem<T>(T NewItem) where T : new()  // not required, but useful
{
    SQLiteConnection conn = new SQLiteConnection("xx");
    var result = conn.Delete<T>(NewItem);
    return true;
}
public void CreateTable<T>() where T : new()          // not required, but useful
{
    SQLiteConnection conn = new SQLiteConnection("xx");
    conn.CreateTable<T>();
    conn.Close();
}
public List<T> GetAllItems<T>(string SelTable) where T : new()
{
    SQLiteConnection conn = new SQLiteConnection("xx");
    List<T> MyItems = conn.Table<T>().ToList();
    conn.Close();
    return MyItems;
}
于 2021-08-09T18:53:24.947 回答