2

我想创建一个创建类实例的 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 

但是这段代码无法编译。

4

2 回答 2

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
于 2008-09-29T16:39:30.677 回答
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
于 2008-09-29T16:54:12.777 回答