使用OleDbConnection的C#中的泛型

Dan*_*gne 0 c# generics oledb

我没有为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
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

SLa*_*aks 5

你正在寻找约束:

public class DatabaseConnector<TConnection> where TConnection : DbConnection, new() {
Run Code Online (Sandbox Code Playgroud)