3

我使用 System.Data.SQLite 和 C# 来访问 SQLite 数据库/表。出于懒惰和快速开发的原因,我创建了自己的类库,将一些 System.Data.SQLite 方法封装在一个方法中,并创建了许多常见的数据库例程(方法),以减少访问数据时的工作量。

如果我继承 System.Data.SQLite 库而不是引用它将帮助我优化我的工作,¿这可能吗?¿ 请你举个例子好吗?

4

2 回答 2

1

可以从 SQLite 继承并对某些类进行添加,尤其是 SQLiteConnection。但是,您将无法在任何地方使用您自己的类,因为 SQLite 将在内部创建许多类,例如 SQLiteCommand 和 SQLiteParameter,并且您无法告诉 SQLite 使用您的自定义版本。有一个 SQLiteFactory,但它用于 ADO.NET 数据提供程序集成,SQLite 内部不使用它。

你最好把你的方法分开。如果您希望他们感觉自己是库的一部分,您可以使用扩展方法

于 2010-01-26T02:48:59.380 回答
0

这是一个很好的问题,7 年后我没有找到太多答案!我只需要做一个简单的继承,发现它有点棘手(因为我并不完全熟悉约束泛型类型)。但这就是我最终得到的结果。

using SQLite; // Here using sqlite-net-pcl
using System.Collections.Generic;

namespace SQLiteEx
{
  class SQLiteConnection : SQLite.SQLiteConnection
  {
    // Must provide a constructor with at least 1 argument
    public SQLiteConnection(string path)
      : base(path)
    {
    }

    // With this class, you can automatically append 
    // some kind of global filter like LIMIT 1000 
    string mGlobalFilter = "";
    public string GlobalFilter
    {
      set { mGlobalFilter = value; }
      get { return string.IsNullOrWhiteSpace(mGlobalFilter) ? "" : " " + mGlobalFilter; }
    }

    // You MUST constrain the generic type with "where T : new()"
    // OTHERWISE feel the wrath of:
    // ===================================================================
    //  'T' must be a non-abstract type with a public parameterless 
    //  constructor in order to use it as parameter 'T' in the generic 
    //  type or method 'SQLiteConnection.Query<T>(string, params object[])'
    // ===================================================================
    public List<T> Query<T>(string sql) where T : new()
    {
      return base.Query<T>(sql + GlobalFilter);
    }
  }
}
于 2017-02-14T22:20:54.510 回答