加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 为什么编译器认为这是Object而不是DataRow?

发布时间:2020-12-17 07:26:52 所属栏目:百科 来源:网络整理
导读:我正在使用LINQ查询将DataTable对象中的数据转换为自定义POCO对象的简单IEnumerable. 我的LINQ查询是: Dim dtMessages As DataTable '...dtMessages is instantiated ByRef in a helper data access routine... ' Dim qry = From dr As DataRow In dtMessag
我正在使用LINQ查询将DataTable对象中的数据转换为自定义POCO对象的简单IEnumerable.

我的LINQ查询是:

Dim dtMessages As DataTable

    '...dtMessages is instantiated ByRef in a helper data access routine... '

    Dim qry = From dr As DataRow In dtMessages.Rows
              Select New OutboxMsg With {
                  .ComputerID = dr(dcComputerID),.MessageData = dr(dcMessageData),.OutBoxID = dr(dcOutBoxID),.OutBoxReceivedID = dr(dcOutBoxReceivedID),.TrxDate = dr(dcTrxDate)
              }

但是,编译器在Dr As DataRow下发出警告消息,并显示以下消息:

Option Strict On disallows implicit conversions from ‘Object’ to ‘System.Data.DataRow’.

为什么我会收到此错误,我需要做些什么才能修复它?我原以为dtMessages.Rows返回了一个DataRow类型的集合.这不正确吗?

解决方法

Lok at DataTable.Rows – 它是一个DataRowCollection,它只实现IEnumerable,而不是IEnumerable(Of DataRow).

幸运的是,在DataTableExtensions中有一个扩展方法,它允许你调用AsEnumerable()而不是行; AsEnumerable返回一个IEnumerable(Of DataRow):

Dim qry = From dr As DataRow In dtMessages.AsEnumerable()
          ...

(我更喜欢使用dt.Rows.Cast(Of DataRow),因为它对可能失败的东西的印象较少.它更适合DataTable.两者都可以工作.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读