如何基于传递给VB.NET泛型方法的类型执行条件逻辑
时间:2020-03-06 14:53:00 来源:igfitidea点击:
我想创建一个VB.NET通用工厂方法,该方法创建类的实例(作为控件容器的本地反转)。如果我将接口IDoSomething作为通用参数传递,我想返回DoSomething的一个实例(实现IDoSomething)。我无法弄清楚if语句的语法。我想写一些类似的东西:
Public Function Build(Of T) as T
If T Is IDoSomething then
Return New DoSomething()
ElseIf T Is IAndSoOn Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub
但是此代码无法编译。
解决方案
Public Function Build(Of T) As T
Dim foo As Type = GetType(T)
If foo Is GetType(IDoSomething) Then
Return New DoSomething()
...
End If
End Function
Public Function Build(Of T) as T
If T.gettype Is gettype(IDoSomething) then
Return New DoSomething()
ElseIf T.gettype Is gettype(IAndSoOn) Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub

