首页 > 解决方案 > Pass a global array to routine for altering using vb.net

问题描述

I have various classes, and am trying to make routines that can edit global arrays for the respective classes. Let me explain..

Let's say one class is a person. Contained in this class is NAME, SSN, DOB, ADDRESS(as an object), etc.

Another class would be address. Contained in this class is NUMBER, STREET, CITY, STATE, ZIPCODE.

I have global arrays which hold each object for those classes. So I have an array of people and an array of addresses.

 Public Shared peopleArr() as peopleClass
 public shared addressArr() as addressClass

I am writing a method to resize the arrays as objects are added. So if a person is added the routine will check to see whether or not the array is empty and will subsequently add an empty spot creating a new object.

 redim preserve peopleArr(0 to 1)
 peopleArr(1) = new personClass

I would like one routine to complete this task no matter what type of array is being altered, but I keep getting an error "Option Strict On disallows narrowing from type 'Object()' to type 'PersonClass()' in copying the value 'ByRef' parameter 'objectArray' back to the matching argument.

If I turn off option strict then I get an error at runtime:

System.InvalidCastException: 'Unable to cast object of type 'System.Object[]' to type 'SMv3._0.personClass[]'.'

Basically, whether personArr or addressArr is passed, I'd like the routine to resize it and create a new item of the respective class, and actually make that change to the global array.

Here is the main call: CreateRemoveObjectArraySpot(globalVariables.personArr(), "")

and here the the routine:

 Public Sub CreateRemoveObjectArraySpot(ByRef objectArray As Object(), deleteString As String)
    Try
        If deleteString = "" Then 'if deletestring is "" then an array spot will be created
            If objectArray Is Nothing Then
                ReDim objectArray(0 To 0)
                objectArray(0) = New Object
            Else

            End If
        Else 'if deletestring is not blank then the array spot containing the string will be deleted

        End If
    Catch ex As Exception
        ErrorDisplay(ex)
    End Try
End Sub

标签: vb.net

解决方案


推荐阅读