0

我没有为 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
            );
        }
    }
}

有没有办法解决?或者也许是另一个可以处理多个版本的类?

4

3 回答 3

5

您正在寻找约束:

public class DatabaseConnector<TConnection> where TConnection : DbConnection, new() {
于 2012-10-22T18:22:50.180 回答
1

尝试where在你的类定义中使用:

 class DatabaseConnector<CONNECTION> where CONNECTION: DbConnection

像这样,您将能够使用公共类中定义的方法。

之后您需要为命令和您需要的所有其他功能创建一个类似的类。

于 2012-10-22T18:27:13.737 回答
0

那解决了它!我从来没有想过使用接口。

public class DatabaseConnector<CN, TRANS, CMD, DA, PARAM>
    where CN:IDbConnection
    where TRANS:IDbTransaction
    where CMD:IDbCommand
    where DA:IDbDataAdapter
    where PARAM:IDbDataParameter
于 2012-10-22T18:51:09.303 回答