tailieunhanh - Visual Basic .NET The Complete Reference phần 7

Truyền mảng đến các phương pháp dòng đầu tiên ném một ngoại lệ làm cho việc sử dụng một chỉ số thấp hơn so với cơ sở 0 (1). Đây không phải là một lỗi thông thường, bởi vì nó là rõ ràng của mảng ràng buộc thấp hơn không phải là một giá trị chỉ số ít hơn 0. | Passing Arrays to Methods The first line that throws an exception makes use of an index that is lower than the base of 0 1 . This is not a common error because it is obvious that the array s lower bound is not an index value less than 0. But the second error is more common because it is not difficult to inadvertently reference an element beyond the upper bound of the array especially when you use magic numbers in your code. The array sAlarms has only five elements 0 to 4 but the index is zero-based so the upper bound is actually 4 and element 5 does not exist. The NullReferenceException is raised when you try to work with an array object that has been declared without elements. The following code which escapes detection if Option Explicit is set to Off will thus not work unless it is properly constructed and initialized Alarms To fix it you need to declare the array with elements remember the name and the braces are just a reference variable to the array object itself. If you need to declare the array now and then provide the length number of elements later declare the array with one zero element and then ReDim the array later to expand it ReDim Preserve Alarms numElements Here numElements represents a variable that sets the new length of the array. The two SafeArray exceptions are raised when the rank or data types of unmanaged so-called safe arrays differ from what s expected the target signatures in the managed world. Passing Arrays to Methods We can easily pass an array as an argument to a method. To accomplish this you just have to leave the brackets off the end of the array name when you do the passing. Have a look at the following statement SortArray sAlarms This code passes the array sAlarms to the method SortArray. Why do we not need the brackets and the element Length information The arrays do not need to schlep such extra baggage when they get passed around because the array object is aware of its own size and the actual array object remains put. The .

TỪ KHÓA LIÊN QUAN