简体   繁体   中英

Generics in C# with OleDbConnection

Rather than maintaining a few different database access layers for OleDbConnection, MySqlConnection, OdbcConnection, and Db2Connection, I was trying to figure out a way to use generics. However, I get an error when I try to compile the code, I get errors when I try to access the class's methods or properties.

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
            );
        }
    }
}

Is there any way around this? Or perhaps another class that can handle the many versions?

您正在寻找约束:

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

Try to use the where in your class definition:

 class DatabaseConnector<CONNECTION> where CONNECTION: DbConnection

Like this you will be able to use the methods defined in the common class.

you will need after that to make a similar class for command and all the other functions that you need.

That fixed it! It never occurred to me to use interfaces.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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