我想创建一个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
但是这段代码没有编译。
答案 0 :(得分:4)
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
答案 1 :(得分:0)
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