0

我正在寻找一个从 .net Framework 2.0 开始的解决方案,现在已经升级到 Framework 4.0,所以我可能在Imports某处缺少所需的参考和/或行,我想......

我有一个 LINQ 查询,格式如下:

Dim x = Aggregate myDataRow As System.Data.DataRow In myDataTable _
        Where (booleanCondition1) _
        AndAlso (booleanCondition2) _
        AndAlso (booleanCondition3) _
        Into Count()

我收到编译错误“ Definition of method 'Count' is not accessible in this context”。

据我从文献中可以看出,Count() 函数应该可用(并且显然应该注册为关键字)。

我究竟做错了什么?

编辑:

我刚刚将我的代码更改为直接的 Select 方法,如下所示:

Dim x = (From myDataRow As System.Data.DataRow In myDataTable _
        Where (booleanCondition1) _
        AndAlso (booleanCondition2) _
        AndAlso (booleanCondition3) _
        Select myDataRow)

当我尝试获取.Countx 时,我收到消息“ 'Count' is not a member of 'System.Data.EnumerableRowCollection(Of System.Data.DataRow)”,根据 MSDN,它是.

现在完全糊涂了。

4

1 回答 1

1

首先,我们看一下EnumerableRowCollection(Of TRow),注意它Count是一个扩展方法:

Count<TRow>() 超载。返回序列中元素的数量。(由 定义Enumerable。)

Enumerable本身有这个信息:

命名空间: System.Linq
程序集: System.Core(在 System.Core.dll 中)

请注意,您始终可以在 MSDN 帮助中找到有关程序集和命名空间的信息。两者都很重要,并且类型的命名空间和它所在的程序集之间没有一一对应的关系。

那么,接下来,让我们看看扩展方法。不幸的是,它是这样说的:

Typically, the module in which an extension method is defined is not the same module as the one in which it is called. Instead, the module that contains the extension method is imported, if it needs to be, to bring it into scope

and then doesn't really elaborate fuller on what it means for the module to be in scope. It does hint at it towards the end though:

When two extension methods that have identical signatures are in scope and accessible, the one with higher precedence will be invoked. An extension method's precedence is based on the mechanism used to bring the method into scope. The following list shows the precedence hierarchy, from highest to lowest.

  • Extension methods defined inside the current module.

  • Extension methods defined inside data types in the current namespace or any one of its parents, with child namespaces having higher precedence than parent namespaces.

  • Extension methods defined inside any type imports in the current file.

  • Extension methods defined inside any namespace imports in the current file.

  • Extension methods defined inside any project-level type imports.

  • Extension methods defined inside any project-level namespace imports.

Since the first two bullets aren't relevant to your situation, only the remainder apply. And they all deal with imports

Imports:

The Imports statement enables types that are contained in a given namespace to be referenced directly.

Hopefully, from all of the above, you can see why having a reference to the correct assembly, by itself, was insufficient, and you also needed to add an import.

于 2013-10-16T14:47:52.510 回答