有没有一种方法可以将给定的属性标识符作为VB中的参数传递给Sub?

时间:2019-02-17 15:36:15

标签: vb.net

我正在尝试创建一个通用的BubbleSort子例程,以在整个程序中使用。因此,我希望能够按任何给定的属性(例如,索引,运行状况,名称等)对列表进行排序。我的问题是,我似乎无法将属性标识符传递给子对象。我该如何实施呢?

我试图将属性作为对象传入,但没有用。

我试图调用子程序:

    AscendingBubbleSort(Party, Character.Health)

潜艇本身:

Sub AscendingBubbleSort(ByRef List As List(Of Object), ByRef ListProperty As Object)

    Dim Swap As Boolean = False
    Dim Temp As New Object

    Do

        Swap = False

        For i = 0 To ((List).Count - 2)

            If List(i).ListProperty < List(i + 1).ListProperty Then

                Temp = List(i)

                List(i) = List(i + 1)
                List(i + 1) = Temp

                Swap = True

            End If

        Next

    Loop Until Swap = False

End Sub

我希望“ Party”列表按Ascending Health排序,但由于以下构建错误,我的程序无法编译:

对非共享成员的引用需要一个对象引用

突出显示“ Character.Health”作为违规代码。

1 个答案:

答案 0 :(得分:2)

下面是使用GenericsLamba的示例。

请注意,如果您要按照子例程标题中的指示进行升序排序,则需要将比较从<更改为>

还要注意在参数中使用ByVal而不是ByRef。仅当您要将传入的变量指向子例程中创建的全新实例时,才需要ByRef。

使用此设置,您可以像这样指定要排序的内容:

AscendingBubbleSort(objects, Function(x) x.SomeProperty)
' < or > 
AscendingBubbleSort(objects, Function(x) x.SomeOtherProperty)

代码:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objects As New List(Of SomeClass)
        objects.Add(New SomeClass() With {.SomeProperty = 5, .SomeOtherProperty = "Bob"})
        objects.Add(New SomeClass() With {.SomeProperty = 1, .SomeOtherProperty = "Jane"})
        objects.Add(New SomeClass() With {.SomeProperty = 7, .SomeOtherProperty = "Cathy"})

        AscendingBubbleSort(objects, Function(x) x.SomeOtherProperty)
        For Each sc As SomeClass In objects
            Debug.Print(sc.ToString)
        Next
    End Sub

    Sub AscendingBubbleSort(Of T)(ByVal List As List(Of T), ByVal ListPropery As Func(Of T, Object))
        Dim Swap As Boolean = False
        Dim Temp As New Object

        Do
            Swap = False
            For i = 0 To ((List).Count - 2)
                If ListPropery(List(i)) > ListPropery(List(i + 1)) Then
                    Temp = List(i)

                    List(i) = List(i + 1)
                    List(i + 1) = Temp

                    Swap = True
                End If
            Next
        Loop Until Swap = False
    End Sub

End Class

Public Class SomeClass

    Public Property SomeProperty As Integer
    Public Property SomeOtherProperty As String

    Public Overrides Function ToString() As String
        Return SomeProperty & ": " & SomeOtherProperty
    End Function

End Class