我一直在尝试使用callbyname来编写一个泛型函数,该函数在将目标列表(targetListName)添加到列表之前检查目标列表(targetListName)是否包含某个项目。不幸的是,我似乎无法弄清楚如何使用带有callbyname的.contains。感谢任何帮助!
这是我现在使用的代码。供应和需求都是(字符串)列表。
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
答案 0 :(得分: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建议。
答案 1 :(得分:0)
您可以只使用字符串字典作为键。不确定使用CallByName的真正好处是什么。你能详细说明你试图解决的用例和问题吗?