【问题标题】:Instantiation issue of generic Interface inherited by abstract class抽象类继承的泛型接口的实例化问题
【发布时间】:2017-08-17 06:27:33
【问题描述】:

我正在尝试设计一个可以处理/使用多个数据库的应用程序,我认为将所有内容封装在 Interfaces 下是个好主意,但似乎我偶然发现了第一种方法 我的界面是:

interface IConnect<T>
    {
        T dbConnection(String dbConnectionString);
    }

我的抽象类是:

  abstract class SqliteConnect :Iconnect<SQLiteConnection>
    {
        public abstract SQLiteConnection dbConnection(String dbConnectionString);
    }

具体的实现是:

  class SQLiteSpecialConnect:SqliteConnect
    {
        public override SQLiteConnection dbConnection(String fileToConnect)
        {
            return new SQLiteConnection("Data Source=" + fileToConnect);
        }
    }

但是当我尝试实例化它时,我得到了

Iconnect<SQLiteConnection> sqliteConObj= new SQLiteSpecialConnect().dbConnection("SomeConnectionString");  

cannot implicitly convert type System.Data.SQLite.SQLiteConnection to Iconnect&lt;System.Data.SQLite.SQLiteConnection&gt;

那么我可以使用这个实现还是不行?

【问题讨论】:

  • 什么是“新的 SQLiteSpecialConnect:SqliteConnect()”?它不应该只是“new SQLiteSpecialConnect()”吗?乍一看,其他一切都很好。
  • 错误的复制粘贴...
  • 是的,当然SQLiteConnection != Iconnect&lt;SQLiteConnection&gt;... -- 使用Iconnect&lt;SQLiteConnection&gt; sqliteConObj= new SQLiteSpecialConnect() 然后sqliteConObj.dbConnection("SomeConnectionString")
  • 界面中的约束也可能很有用,如果您不想将它与 DbConnection 以外的任何东西一起使用:where T:DbConnection

标签: c# sqlite generics interface abstract


【解决方案1】:

应该是这样的:

IConnect<SQLiteConnection> sqliteConObj = new SQLiteSpecialConnect();
SQLiteConnection connection = sqliteConObj.dbConnection("SomeConnectionString");

问题是你立即调用方法所以返回类型是 SQLiteConnection

【讨论】:

  • @John - 如果是这样,您可能需要考虑接受这个答案。
猜你喜欢
  • 2012-04-11
  • 2020-12-10
  • 2012-01-27
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多