2012-07-24 57 views
1

這不應該很難回答,但我非常絕望和困惑。我做了執行從數據庫讀取查詢的接口實現接口的MySql和SQlite類

interface IDatabase 
{ 
    DataTable ExecuteReaderCommand(IDbCommand command); 
    IDbCommand GetNewCommand(); 
} 

接下來,我在接口上面創建了兩個不同的類implemetnig。

class MysqlDatabase : IDatabase 
{ 
    public DataTable ExecuteReaderCommand(MySqlCommand command) 
    { 
     DataTable dt = new DataTable(); 
     // ... read db 
     return dt; 
    } 

    public MySqlCommand GetNewCommand() 
    { 
     cnn.Open(); 
     return cnn.CreateCommand(); 
    } 
} 

而且

class SQLiteDatabase : IDatabase 
{ 
String dbConnection; 
    SQLiteConnection cnn; 

    public DataTable ExecuteReaderCommand(SQLiteCommand command) 
    { 
     DataTable dt = new DataTable(); 
     // ... read db 
     return dt; 
    } 

    public SQLiteCommand GetNewCommand() 
    { 
     cnn.Open(); 
     return cnn.CreateCommand(); 
    } 
} 

但我得到的錯誤,這些類不實現接口IDatabase:

MysqlDatabase does not implement interface member 'Database.GetNewCommand()' 
MysqlDatabase.GetNewCommand() cannot implement 'Database.GetNewCommand()' because it does not have the matching return type of 'System.Data.IDbCommand'. 

SQLiteDatabase does not implement interface member Database.ExecuteReaderCommand(System.Data.IDbCommand) 
SQLiteDatabase does not implement interface member 'Database.GetNewCommand()'. SQLiteDatabase.GetNewCommand() cannot implement Database.GetNewCommand() because it does not have the matching return type of 'System.Data.IDbCommand'. 

當我看就SQLiteCommandMySqlCommand他們都實現了IDbCommand

如何在通用界面下使用這些類,以便輕鬆切換它們?

我非常感謝任何答案。

回答

4

當我看就SQLiteCommand和MySqlCommand將他們都器具IDbCommand的

不,他們沒有。他們聲稱他們這樣做,但他們實際上並沒有提供正確的方法。看看IDatabase.GetNewCommand()

IDbCommand GetNewCommand(); 

和您的實現:

public MySqlCommand GetNewCommand() 
{ 
    ... 
} 

他們有不同的返回類型。同樣,您的ExecuteReaderCommand方法參數在IDatabase中,但MySqlCommandMysqlDatabase中。

選項:

  • 使用的「弱類型」的版本顯式接口實現,露出的混凝土類「強類型」的版本。例如,這就是.NET框架中的SqlCommand

  • 製作IDatabase通用的命令的類型是創建和使用:

    public interface IDatabase<TCommand> where TCommand : IDbCommand 
    { 
        DataTable ExecuteReaderCommand(TCommand command); 
        TCommand GetNewCommand(); 
    } 
    
+1

選項1正是我想做的事。你能指點我正確的方向怎麼做?我需要用於MysqLCommand和SQLiteCommand的通用界面。我認爲這是IDbCommand。 – 2012-07-24 17:31:35