VB.NET中的数据类型检查问题

VB.NET中的数据类型检查问题,vb.net,Vb.net,我试图查看datagrid.datasource是否属于特定类型,然后采取不同的操作 if grid.datasource is CollectionBase then ' do sone thing else if grid.datasource is IEnumerable then ' do other thing end if 第一个检查显示CollectionBase是一个类型,不能用作表达式。这是什么意思 更新1: 我检查了一下,似乎我正在向网格发送一个对象数组。有点像顾客[

我试图查看datagrid.datasource是否属于特定类型,然后采取不同的操作

if grid.datasource is CollectionBase then 
' do sone thing 
else if grid.datasource is IEnumerable then 
' do other thing
end if
第一个检查显示CollectionBase是一个类型,不能用作表达式。这是什么意思

更新1:

我检查了一下,似乎我正在向网格发送一个对象数组。有点像顾客[]。如何使其通用,以便获得数组并以某种方式获得计数

试试这个

if grid.datasource.GetType() is GetType(CollectionBase) then 
    Dim myCollection as CollectionBase = TryCast(grid.DataSource, CollectionBase)
    If (myCollection IsNot Nothing) Then
        myCollection.Count
    End If
else if grid.datasource.GetType() is GetType(IEnumerable) then 
    Dim myCollection as IEnumerable= TryCast(grid.DataSource, IEnumerable)
    If (myCollection IsNot Nothing) Then
        myCollection.Count()
    End If
end if

您需要使用
TypeOf…Is…

If TypeOf grid.datasource Is CollectionBase Then
' do sone thing 
Else If TypeOf grid.datasource Is IEnumerable Then
' do other thing
End If

仅使用
Is
检查两个对象的标识。但是,代码中的第二个操作数不是对象,而是类型名。

我的更新应该回答您的更新问题。尽管如果使用
TryCast
您不必预先检查类型,因为如果强制转换失败,它将返回null。