1
    Function keepOnlyDuplicates(ByRef list1 As List(Of Integer), ByRef list2 As List(Of Integer)) As List(Of Integer)
    Dim returnList As New List(Of Integer)
    For Each i As Integer In list1
        For Each j As Integer In list2
            If i = j Then
                returnList.Add(i)
                Exit For
            End If
        Next
    Next
    Return returnList
End Function

この関数を作成して、他の2つの整数から、両方にある整数のみを含む整数の新しいリストを作成しました(個々のリストには重複がありません)。

この関数を変更して、任意のタイプのリストを受け入れ、それに応じたタイプのリストを問題なく返す方法はありますか? 本当に複雑な場合は、他のタイプの別の関数を簡単に作成できます。しかし、どのタイプを呼び出すかだけの問題である場合、どうすればそれを行うことができますか?

ありがとう。

4

1 に答える 1

3
Function keepOnlyDuplicates(Of t As IComparable)(ByRef list1 As List(Of t), ByRef list2 As List(Of t)) As List(Of t)
            Dim returnList As New List(Of t)
            For Each i As t In list1
                For Each j As t In list2

                    If i.CompareTo(j) = 0 Then
                        returnList.Add(i)
                        Exit For
                    End If
                Next
            Next
            Return returnList
        End Function

t が独自の型になる場合:

//完全に比較可能にするために、独自の型を追加しますImplements IComparable

または、このようにします。等しいかどうかのみをチェックする場合は、 関数を変更します

 Function keepOnlyDuplicates(Of t)(ByRef list1 As List(Of t), ByRef list2 As List(Of t)) As List(Of t)

この場合、独自の型に対して equal() をオーバーライドするだけです。に条件を変更

If i.Equals(True) = True Then .
于 2013-06-22T06:22:43.353 に答える