【问题标题】:Why does the compiler think this is an Object instead of a DataRow?为什么编译器认为这是一个 Object 而不是 DataRow?
【发布时间】:2010-08-02 14:40:19
【问题描述】:

我正在使用 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 不允许从“Object”到“System.Data.DataRow”的隐式转换。

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

【问题讨论】:

  • 展示如何声明和实例化 dtMessages。
  • @bzlm 我用更多信息更新了我的帖子
  • 关掉Option Strict!我开玩笑,我开玩笑。
  • @Marc 他应该关闭 VB.NET。 :)
  • @bzlm 虽然我通常更喜欢 C# 而不是 VB.NET,但我在 VB.NET 中编写代码是有报酬的,所以放弃它是一个非常昂贵的决定:-)。

标签: .net vb.net linq casting option-strict


【解决方案1】:

DataTable.Rows - 这是一个DataRowCollection,它只实现IEnumerable,而不是IEnumerable(Of DataRow)

幸运的是,DataTableExtensions 中有一个扩展方法,可以让您调用AsEnumerable() 而不是RowsAsEnumerable 返回IEnumerable(Of DataRow)

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

(与使用 dt.Rows.Cast(Of DataRow) 相比,我更喜欢这个,因为它不会让人觉得可能会失败。它更适合 DataTable。不过两者都可以。)

【讨论】:

    【解决方案2】:

    System.DataTable 类型早于 .Net 中的泛型,因此返回一个普通的旧 IEnumerable 而不是 IEnumerable(Of DataRow),即使它们是 DataRow 的实例。因此,上述查询中dr 的类型是Object 而不是DataRow

    您可以通过使用Cast 扩展方法使集合的类型显式化来解决此问题

    From dr As DataRow in dtMessages.Rows.Cast(Of DataRow)
    

    【讨论】:

      【解决方案3】:

      DataTable.Rows 属性返回一个DataRow 的集合,但是该集合没有实现IEnumerable<DataRow>,而是实现IEnumerable,它作为IEnumerable<Object> 工作。

      您可以使用dtMessages.Rows.Cast<DataRow>() 将集合项显式转换为DataRow

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-03
        • 2013-06-16
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 2016-11-01
        • 2011-05-26
        • 1970-01-01
        相关资源
        最近更新 更多