質問

I'm trying to make my Mode function accept arrays of any type, and I'm not making any progress. Here's what I've got now:

Private Function Mode(ByRef list As Object) As Object
        Dim array() As Object = {}
        Try
            array = CType(list, Object())
        Catch ex As Exception
            MessageBox.Show("Failed to cast array of Objects in Mode function!")
            Return Nothing
        End Try
        Dim uniqueObjects() As Integer = {array(0)}
        Dim frequency() As Integer = {1}
        For i As Integer = 0 To array.Length - 1
            For j As Integer = 0 To uniqueObjects.Length - 1 'loop through frequency
                If array(i) = uniqueObjects(j) Then
                    frequency(j) += 1
                    Exit For
                ElseIf j = uniqueObjects.Length - 1 Then
                    ReDim Preserve uniqueObjects(uniqueObjects.Length) 'add to unique objects array
                    uniqueObjects(uniqueObjects.Length - 1) = array(i)
                    ReDim Preserve frequency(frequency.Length) 'increment frequency
                    frequency(frequency.Length - 1) += 1
                End If
            Next
        Next

        Return uniqueObjects(System.Array.IndexOf(frequency, frequency.Max))
    End Function

I would normally get rid of the slow call to CType and just pass an array of Objects to the function, but It gives me a weird error when I pass an array of integers to the function:

Error 1 Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Object' because 'Integer' is not a reference type. {filename}.vb {line} {column} {project name}

This is turning out to be much trickier than I had expected. Can anyone offer advice?

役に立ちましたか?

解決

How about making this a generic function?

Private Function Mode(Of T)(ByRef array As T()) As Object
    '...
End Function

Or

Private Function Mode(Of T)(ByRef array As T()) As T()
    '...
End Function

Then you do:

Dim obj As Object = Mode(Of Integer)({0, 1, 2, 3})

Or:

Dim obj As Integer() = Mode(Of Integer)({0, 1, 2, 3})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top