gpt4 book ai didi

c# - MySql 和 SQlite 类实现接口(interface)

转载 作者:行者123 更新时间:2023-11-29 04:50:59 25 4
gpt4 key购买 nike

这应该不难回答,但我是如此绝望和困惑。我制作了用于从数据库执行读取查询的接口(interface)

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

接下来,我在接口(interface)之上创建了两个不同的实现类。

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 接口(interface)的错误:

 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

如何在通用接口(interface)下使用这些类,以便轻松切换它们?

非常感谢您的回答。

最佳答案

When I look on the SQLiteCommand and MySqlCommand they both implements IDbCommand

不,他们没有。他们声称他们这样做,但他们实际上并没有提供正确的方法。查看 IDatabase.GetNewCommand():

IDbCommand GetNewCommand();

和您的实现:

public MySqlCommand GetNewCommand()
{
...
}

它们有不同的返回类型。同样,您的 ExecuteReaderCommand 方法参数在 IDatabase 中是 IDbCommand,但在 MysqlDatabase 中是 MySqlCommand

选项:

  • 为“弱类型”版本使用显式接口(interface)实现,在具体类上公开“强类型”版本。例如,这就是 SqlCommand 在 .NET 框架中所做的。

  • 使 IDatabase 在其创建和使用的命令类型中通用:

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

关于c# - MySql 和 SQlite 类实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com