可转换性。
必须能够在两个数组的元素类型之间执行转换(扩大或收缩)。 未能满足此要求的一个示例是尝试在
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.
数组的基础类型
如果最初使用特定类声明数组,则其基础元素类型为该类。 如果随后将其设置为另一个类的数组,则这两个类之间必须存在转换。
以下面的示例中,students
是 student
数组。 由于 String
与 student
之间不存在任何转换,因此最后一个语句会失败。
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