HOW TO:指派一個陣列至另一個陣列 (Visual Basic)How to: Assign One Array to Another Array (Visual Basic)

因為陣列是物件,您可以像其他物件類型的指派陳述式中使用它們。Because arrays are objects, you can use them in assignment statements like other object types. 陣列變數會保留構成的陣列項目和的順位和長度的資訊,將資料指標,並指派複製只有此指標。An array variable holds a pointer to the data constituting the array elements and the rank and length information, and an assignment copies only this pointer.

若要指派一個陣列至另一個陣列To assign one array to another array

  1. 請確定兩個陣列具有相同陣序 (維度數目) 和相容的項目資料型別。Ensure that the two arrays have the same rank (number of dimensions) and compatible element data types.

  2. 您可以使用標準的指派陳述式,將來源陣列指派給目的地陣列。Use a standard assignment statement to assign the source array to the destination array. 請勿遵循任一陣列名稱,加上括弧。Do not follow either array name with parentheses.

    Dim formArray() As System.Windows.Forms.Form
    Dim controlArray() As System.Windows.Forms.Control
    controlArray = formArray

當您指派一個陣列至另一個時,適用下列規則:When you assign one array to another, the following rules apply:

  • 相同的陣序規範。Equal Ranks. 目的陣列的陣序 (維度數目) 必須是相同的來源陣列。The rank (number of dimensions) of the destination array must be the same as that of the source array.

    提供兩個陣列的陣序規範是相等的不需要相同維度。Provided the ranks of the two arrays are equal, the dimensions do not need to be equal. 指定維度中的項目數可以在指派期間變更。The number of elements in a given dimension can change during assignment.

  • 項目型別。Element Types. 可能是這兩個陣列必須有參考的型別項目或兩個陣列必須實值型別項目。Either both arrays must have reference type elements or both arrays must have value type elements. 如需詳細資訊,請參閱 Value Types and Reference TypesFor more information, see Value Types and Reference Types.

    • 如果兩個陣列值型別項目,項目資料類型必須完全相同。If both arrays have value type elements, the element data types must be exactly the same. 唯一的例外是,您可以將指派的陣列Enum的基底型別陣列的項目EnumThe only exception to this is that you can assign an array of Enum elements to an array of the base type of that Enum.

    • 如果兩個陣列都具有參考型別項目,將來源項目型別必須衍生自目的項目型別中。If both arrays have reference type elements, the source element type must derive from the destination element type. 這種情況時,兩個陣列都具有相同的繼承關聯性,做為其項目。When this is the case, the two arrays have the same inheritance relationship as their elements. 這就叫做陣列共變數This is called array covariance.

編譯器會報告錯誤,如果違反上述規則,例如如果資料類型不相容或陣序規範不相等。The compiler reports an error if the above rules are violated, for example if the data types are not compatible or the ranks are unequal. 您可以新增錯誤處理您的程式碼,請確定陣列相容,然後再嘗試指派。You can add error handling to your code to make sure that the arrays are compatible before attempting an assignment. 您也可以使用TryCast 運算子關鍵字,如果您想要避免擲回例外狀況。You can also use the TryCast Operator keyword if you want to avoid throwing an exception.

另請參閱See also