我有一些类似的代码:
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
Run Code Online (Sandbox Code Playgroud)
这些查找都很好用。我要尝试的是根据另一个变量的类型调用适当的LookUp。看起来像...
Lookup(Of GetType(MyStringVariable))("Testing")
Run Code Online (Sandbox Code Playgroud)
我尝试使用Google进行搜索,但是很难找到合适的搜索。谁能告诉我该怎么做?
您没有为要调用的方法指定完整签名,但是我的灵通能力告诉我,这是这样的:
Function Lookup(Of T)(key As String) As T
Run Code Online (Sandbox Code Playgroud)
而且您希望避免重复Integer以下示例中的两次:
Dim x As Integer
x = Lookup(Of Integer)("foo");
Run Code Online (Sandbox Code Playgroud)
问题在于,只有在参数上下文中使用类型参数时才能推导类型参数,而在返回值上下文中则不会使用。因此,您需要一个带有ByRef参数的辅助函数来完成技巧:
Sub Lookup(Of T)(key As String, ByRef result As T)
T = Lookup(Of T)(key)
End Sub
Run Code Online (Sandbox Code Playgroud)
这样,您可以编写:
Dim x As Integer
Lookup("foo", x);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2569 次 |
| 最近记录: |