首页 > 解决方案 > Option Strict 不允许使用 IEnumerable 进行后期绑定

问题描述

Dim distinctJoints As IEnumerable
distinctJoints = From row In spotsTable.AsEnumerable()
                                        Group row By Key = row("FUNCJOINTCODE") Into Group
                                        Select Key, Group

_evaluatedJointsCount = (From row In spotsTable.AsEnumerable()
                        Group row By Key = row("FUNCJOINTCODE") Into Group
                        Select Key, Group).Count()

'Process each joint
For Each currentJoint In distinctJoints
    Dim currentJointKey As String = currentJoint.Key

因为上面的代码currentJoint.Key在选项严格打开后显示后期绑定错误。你能帮我解决这个问题吗?

标签: asp.netvb.net

解决方案


首先,让我祝贺您将代码移向Option Strict On! 一开始可能会做一些工作,但从长远来看会有所回报,因为会在编译时而不是在运行时发现很多错误。

也就是说,让我们看看你的问题。这里:

Dim distinctJoints As IEnumerable

您声明distinctJoints为非通用IEnumerable. 非泛型 IEnumerableObject在迭代时返回类型项。该类型Object不包含Key方法。这就是您收到编译时错误的原因。

由于您的 LINQ 查询返回匿名类型的通用 IEnumerable,因此解决方案是改用类型推断。在您的项目属性中激活Option Infer On(如果您尚未这样做)并让编译器推断正确的数据类型:

' Dim distinctJoints As IEnumerable <-- remove this
Dim distinctJoints = From row In spotsTable.AsEnumerable()
                     Group row By Key = row("FUNCJOINTCODE") Into Group
                     Select Key, Group

推荐阅读