• 秩相等。 两个数组的秩必须相同,也就是说,它们必须具有相同的维数。 但是,各个维度的长度不必相同。

  • 元素数据类型。 两个数组的元素的数据类型必须是引用类型。 由于至少涉及一种值类型,因此不能将 Integer 数组转换为 Long 数组,甚至不能转换为 Object 数组。 有关更多信息,请参见 Value Types and Reference Types

  • 可转换性。 必须能够在两个数组的元素类型之间执行转换(扩大或收缩)。 未能满足此要求的一个示例是尝试在 String 数组和派生自 System.Attribute 的类的数组之间执行转换。 这两种类型没有任何共同之处,它们之间不存在任何类型的转换。

    将一种数组类型转换为另一种数组类型是扩大或收缩,这取决于各个元素的转换是扩大还是收缩。 有关详细信息,请参阅 Widening and Narrowing Conversions

    转换为 object 数组

    在未初始化的情况下声明 Object 数组时,只要该数组保持未初始化状态,其元素类型就为 Object 。 将其设置为特定类的数组时,它将采用该类的类型。 但是,其基础类型仍为 Object ,你随后可以将其设置为不相关类的另一个数组。 由于所有类均派生自 Object ,因此可以将数组的元素类型从任何类更改为任何其他类。

    在下面的示例中,类型 student String 之间不存在任何转换,但这两种类型都派生自 Object ,因此所有分配都有效。

    ' Assume student has already been defined as a class.  
    Dim testArray() As Object  
    ' testArray is still an Object array at this point.  
    Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"}  
    testArray = New student(3) {}  
    ' testArray is now of type student().  
    testArray = names  
    ' testArray is now a String array.  
    

    数组的基础类型

    如果最初使用特定类声明数组,则其基础元素类型为该类。 如果随后将其设置为另一个类的数组,则这两个类之间必须存在转换。

    以下面的示例中,studentsstudent 数组。 由于 Stringstudent 之间不存在任何转换,因此最后一个语句会失败。

    Dim students() As student  
    Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"}  
    students = New Student(3) {}  
    ' The following statement fails at compile time.  
    students = names  
    
  • Visual Basic 中的类型转换
  • 隐式转换和显式转换
  • 字符串和其他类型之间的转换
  • 如何:在 Visual Basic 中将一个对象转换为其他类型
  • Type Conversion Functions
  •