0

我一直在尝试使用 callbyname 编写一个通用函数,该函数在将目标列表(targetListName)添加到列表之前检查它是否包含某个项目。不幸的是,我似乎无法弄清楚如何将 .contains 与 callbyname 一起使用。感谢任何帮助!

这是我现在使用的代码。供应和需求都是列表(字符串)。

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    Select Case targetListName.ToLower
        Case "supply"
            If supply.Contains(item) = False Then supply.Add(targetListName)
        Case "demand"
            If demand.Contains(item) = False Then supply.Add(targetListName)
        Case Else
            'bugcatch
    End Select
End Sub

我想理想地使用这样的东西:

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    If CallByName(Me, targetListName, [Method]).Contains(item) = false Then
        CallByName(Me, targetListName, [Set]).Add(item)
    End If
End Sub
4

2 回答 2

0

You could just have a dictionary of lists with string as your key. Not sure what the real benefit of is of using CallByName. Could you elaborate on that more on the use case and problem you are trying to solve?

于 2013-09-09T00:36:11.030 回答
0

不幸的是,该CallByName功能不能那样工作。请参阅http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.interaction.callbyname.aspx

一种解决方法可能是这样做:

Public Function getListByName(ByVal targetListName As String) As List(of Object)
    Select Case targetListName.ToLower
        Case "supply"
            return supply
        Case "demand"
            return demand
        Case Else
            'bugcatch
    End Select
    return Nothing
End Function

Public Sub addItem(ByVal item As String, ByVal targetListName As String)
    dim list As List(of Object) = GetListByName(targetListName)
    If not list.Contains(item) Then
        list.Add(item)
    End If
End Sub

或者,您可以使用反射来获取您的列表:

Public Function getListByName(ByVal targetListName As String) As Object
    dim field = Me.GetType().GetField(targetListName)
    If field IsNot Nothing then
        return field.GetValue(Me)
    End If
    return Nothing
End Function

如果可能的话,如果列表的数量不经常改变,我会使用@user2759880 的建议。

于 2013-09-09T00:33:46.957 回答