将列表传递给方法并将其循环以获取值

时间:2012-10-22 00:44:02

标签: vb.net oop

我需要将强类型类集合List传递给函数,并且需要循环遍历该类集合的属性,并需要检查这些属性值字符串是否包含任何非法XML字符。请举例说明如何进行上述情况。

2 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点

使用对象列表 -

Dim T As List(Of mClass) = New List(Of mClass)
MyFunction(T)

Dim T2 As List(Of mClass2) = New List(Of mClass2)
MyFunction(T2)


Private Sub MyFunction(ByVal myList As List(Of Object))
    For Each MyCls In myList
        If TypeOf MyCls Is mClass Then
            Dim cInst As mClass = DirectCast(MyCls, mClass)
            cInst.P = 
        ElseIf TypeOf MyCls Is mClass2 Then
            Dim cInst As mClass2 = DirectCast(MyCls, mClass2)
            cInst.A = 
        End If
    Next
End Sub

或者只是将列表作为对象传递 -

Dim T As List(Of mClass) = New List(Of mClass)
MyFunction(T)

Dim T2 As List(Of mClass2) = New List(Of mClass2)
MyFunction(T2)


Private Sub MyFunction(ByVal myList As Object)
    If TypeOf myList Is List(Of mClass) Then
        Dim cInst As List(Of mClass) = DirectCast(myList, List(Of mClass))
        For Each MyCls As mClass In cInst
            MyCls.P = 
        Next
    ElseIf TypeOf myList Is List(Of mClass2) Then
        Dim cInst As List(Of mClass2) = DirectCast(myList, List(Of mClass2))
        For Each MyCls As mClass2 In cInst
            MyCls.A = 
        Next
    End If
End Sub

这可能会有所帮助 如果要

,可以为Para定义变量数据类型
Dim T As Integer
Dim T2 As String
MyFunction(Of Integer)(T)
MyFunction(Of String)(T2)

Private Sub MyFunction(Of AnyNameForType)(ByVal myList As AnyNameForType)

End Sub

答案 1 :(得分:0)

Dim T As List(Of mClass) = New List(Of mClass)
myfunction(T)


Private Function MyFunction(ByVal myList As List(Of mClass))
    For Each MyCls As mClass In myList
        MyCls.mProperty = 
    Next
End Function