繁体   English   中英

如何在C#中继承System.Data.SQLite

[英]How to inherit System.Data.SQLite in C#

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

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

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

你最好保持你的方法分开。 如果您希望他们觉得他们是图书馆的一部分,您可以使用扩展方法

这是一个很好的问题,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);
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM