我一直试图使用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发布于 2013-09-09 00:36:11
您可以只需要一本以字符串作为键的列表字典。不确定使用CallByName的真正好处是什么。你能详细说明一下你想要解决的用例和问题吗?
发布于 2013-09-09 00:33:46
不幸的是,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的建议。
https://stackoverflow.com/questions/18689993
复制相似问题