【问题标题】:Portable Mode Function in Visual BasicVisual Basic 中的可移植模式函数
【发布时间】:2014-01-31 19:30:51
【问题描述】:

我正在尝试让我的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 ​​类型“整数的一维数组”的值无法转换为“对象的一维数组”,因为“整数”不是引用类型。 {filename}.vb {line} {column} {项目名称}

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

【问题讨论】:

    标签: arrays vb.net object analysis


    【解决方案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})
    

    【讨论】:

    • 不,也试过了。然后If array(i) = uniqueObjects(j) Then 行不起作用。它说 operator = 没有为 T 类型的对象定义。
    • 您需要将其更改为 'If (Object.Equals(array(i), uniqueObjects(j))) Then' 并且您应该将 uniqueObjects 声明为 T 的数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2010-09-16
    相关资源
    最近更新 更多