Visual Basic中的可移植模式功能

时间:2014-01-31 19:30:51

标签: arrays vb.net object analysis

我正在尝试让我的Mode函数接受任何类型的数组,但我没有取得任何进展。这就是我现在所拥有的:

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

我通常会摆脱对CType的缓慢调用,只是将一个对象数组传递给函数,但是当我将一个整数数组传递给函数时,它给了我一个奇怪的错误:

  

错误1类型'1维数组的整数'的值无法转换为'1维数组的对象',因为'整数'不是引用类型。 {filename} .vb {line} {column} {project name}

这比我预期的要复杂得多。有人可以提供建议吗?

1 个答案:

答案 0 :(得分:1)

如何将此作为通用功能?

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

或者

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

然后你做:

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

或者:

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