方法返回一个接口 [英] Method return an interface

查看:179
本文介绍了方法返回一个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想在这行code

IDataReader myReader = questDatabase.ExecuteReader(getQuest);

我使用DAAB,但我无法理解,什么是一个事实的方法的ExecuteReader(的DbCommand)返回一个IDataReader的接口的含义。

I'm using DAAB but I can't understand how and what's the meaning of the fact the method ExecuteReader(DbCommand) returns an IDataReader Interface.

任何人都可以说明,请

推荐答案

它可以让你对你的DataReader不知道哪种类型的DataReader您正在使用的需要(即 SqlDataReader的,OleDbDataReader,EtcDataReader ),所以,如果有一天你想你正在使用它不会影响你的逻辑改变DataReader的,换句话说,它为您提供了抽象。 例如:

It allows you to you DataReader without the need of knowing which type of DataReader you are using (i.e. SqlDataReader, OleDbDataReader, EtcDataReader), so if someday you want to change the datareader you are using it won't impact you logic, in other words it gives you abstraction. For example :

您可以使用

IDbCommand command = GiveMeSomeCommand();
IDataReader r = command.ExecuteReader();

不知道这些供应商使用的是

without knowing which provider you are using

可以是:

private static IDbCommand GiveMeSomeCommand()
{
    return new OleDbCommand();
}

,或者它可以是

or it can be

private static IDbCommand GiveMeSomeCommand()
{
    return new SqlCommand();
}

或什么的。

编辑:

您也可以使用DBFactories。

You can also use the DBFactories.

DbProviderFactory factory = GiveMeSomeFactory();
IDbCommand command = factory.CreateCommand();
IDataReader r = command.ExecuteReader();

//and create more objects
IDataAdapter adapter = factory.CreateDataAdapter();
IDbConnection conn = factory.CreateConnection();

,然后创建其他层的供应商

and then create your provider in other layer

private DbProviderFactory GiveMeSomeFactory()
{
    if(something)
        return SqlClientFactory.Instance;
    else if(somethingElse)
        return OracleFactory.Instance;
    else if(notThisAndNotThat)
        return MySqlFactory.Instance;
    else
        return WhateverFactory.Instance;

}

这篇关于方法返回一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆