簡體   English   中英

具有OleDbConnection的C#中的泛型

[英]Generics in C# with OleDbConnection

我沒有為OleDbConnection,MySqlConnection,OdbcConnection和Db2Connection維護一些不同的數據庫訪問層,而是試圖找到一種使用泛型的方法。 但是,嘗試編譯代碼時會出錯,嘗試訪問類的方法或屬性時會出錯。

public class DatabaseConnector<CONNECTION> {
    private CONNECTION connection = default(CONNECTION);
    public bool IsConnected {
        get {
            return (
                this.connection != null &&
                // error on connection.State on the following two lines
                this.connection.State != System.Data.ConnectionState.Closed &&
                this.connection.State != System.Data.ConnectionState.Broken
            );
        }
    }
}

有沒有辦法解決? 還是另一個可以處理許多版本的類?

您正在尋找約束:

public class DatabaseConnector<TConnection> where TConnection : DbConnection, new() {

嘗試在類定義中使用where

 class DatabaseConnector<CONNECTION> where CONNECTION: DbConnection

這樣,您將能夠使用公共類中定義的方法。

之后,您需要為命令和所需的所有其他功能創建一個類似的類。

修好了! 我從來沒有想過使用接口。

public class DatabaseConnector<CN, TRANS, CMD, DA, PARAM>
    where CN:IDbConnection
    where TRANS:IDbTransaction
    where CMD:IDbCommand
    where DA:IDbDataAdapter
    where PARAM:IDbDataParameter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM