开发者

How to convert/cast SqlDataReader to IDatareader

开发者 https://www.devze.com 2023-01-26 02:59 出处:网络
What is the easiest way to cast a SqlDataReader to IDatareader. Or is it eas开发者_开发知识库ier / possible to convert a List<> object to a IDataReader

What is the easiest way to cast a SqlDataReader to IDatareader.

Or is it eas开发者_开发知识库ier / possible to convert a List<> object to a IDataReader


What is the easiest way to convert a SqlDataReader to IDatareader

Since SqlDataReader implements IDataReader, this is just an implicit cast:

SqlDataReader typedReader = ...
IDataReader untypedReader = typedReader;


What is the easiest way to convert a SqlDataReader to IDatareader

You can not. A SqlDataReader CLASS is not an IDataReader interfadce.

For casting (assign to variable) use

IDataReader untypedReader = typedReader; 

BUT: this is NOT a conversion. It is a cast. A conversion to an inteerface is per defintiion not possible as interfaces can not be instantiated.


A SqlDataReader is an IDataReader (it implements the interface), so you don't have to convert it at all. Anywhere your code expects an IDataReader, you can use the Sql implementation.

// Given a method with this signature
public void ProcessData(IDataReader reader);

// You can do this
SqlDataReader sqlReader = command.ExecuteReader();
ProcessData(sqlReader);

As for List<T> and IDataReader: apart from being enumerable these do very different things. The most conspicuous difference is that data readers offer access to columnar data (primarily because it implements the IDataRecord interface), which doesn't make sense for most lists.

You could implement an adapter that provides access to a List<T> through the data reader interface, but it would be a poor fit and a fair amount of work.


Or you can just cast it, but as has been stated, it's largely unnecessary unless you're creating or using a generic interface since all the properties and methods of IDbDataReader is available to SqlDataReader.

((IDbDataReader)typedReader).SomeMethod();
0

精彩评论

暂无评论...
验证码 换一张
取 消