我试图使我的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
而只是将Objects数组传递给函数,但是当我将整数数组传递给函数时,这给了我一个奇怪的错误:
错误1由于“整数”不是引用类型,因此无法将类型“整数的一维数组”的值转换为“对象的一维数组”。{filename} .vb {line} {column} {project name}
事实证明,这比我预期的要复杂得多。谁能提供建议?
如何使其成为通用函数?
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})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句