如何使用相同的代码从 DataRow 或 DataReader 中读取数据?
目前,我使用的 SqlDataReader
加载了一个简单的数据库“选择”查询。每行代表一个域对象,因此我像这样膨胀每个对象:
Dim loadedItems As New List(Of Item)
Dim dr As SqlDataReader = GetItemsDataReader()
While dr.Read()
Dim item As Item = GetItemFromData(dr)
loadedItems.Add(item)
End While
我编写的 GetItemFromData 方法看起来像这样:
Private Function GetItemFromData(dr As SqlDataReader) As Item
Dim loadedItem As New Item()
loadedItem.ID = dr("ID")
loadedItem.Name = dr("Name")
'etc., etc.'
Return loadedItem
End Function
在某些情况下,我必须从 DataRow 读取数据> 而不是 SqlDataReader
。但代码是完全相同的!当我查看 GetItemFromData
方法时,我想在 dr
参数中接受更通用的对象类型,以便我可以处理 DataReader
与 DataRow
相同,因为如果我编写了一个要使用 DataRow
的代码,我将在该方法中编写完全相同的代码。有办法做到这一点吗?
Currently, I am using a SqlDataReader
loaded up with a simple database 'Select' query. Each row represents a domain object, so I inflate each object like this:
Dim loadedItems As New List(Of Item)
Dim dr As SqlDataReader = GetItemsDataReader()
While dr.Read()
Dim item As Item = GetItemFromData(dr)
loadedItems.Add(item)
End While
The GetItemFromData
method I wrote looks something like this:
Private Function GetItemFromData(dr As SqlDataReader) As Item
Dim loadedItem As New Item()
loadedItem.ID = dr("ID")
loadedItem.Name = dr("Name")
'etc., etc.'
Return loadedItem
End Function
In some cases, I have to read data from a DataRow
instead of a SqlDataReader
. But the code would be the exact same! As I look at my GetItemFromData
method, I want to accept a more generic type of object in the dr
parameter so that I can treat a DataReader
the same as a DataRow
, since I would be writing the exact same code inside the method if I wrote one that was meant to use a DataRow
. Is there a way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到的唯一方法是包装一些类并实现一个接口 - 类似于:
然后,您必须在将行或读取器传递给您的方法之前包装您的行或读取器:
Only way I can think of off the top of my head would be to wrap a few classes and implement an inferface - something like:
You would then have to wrap your row or reader before passing it to your method:
如何使用
DataTable
代替:更改 GetItemFromData() 方法以采用
DataRow
而不是DataReader
(对于 VB.NET/ C# 混合伪代码)。How about using a
DataTable
instead:Change your GetItemFromData() method to take a
DataRow
instead of aDataReader
(sorry about the VB.NET/C# hybrid pseudo code).