簡體   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