【问题标题】:How do I execute conditional logic based upon the type passed to a VB.NET generic method如何根据传递给 VB.NET 泛型方法的类型执行条件逻辑
【发布时间】:2008-09-29 16:29:16
【问题描述】:

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

但是这段代码无法编译。

【问题讨论】:

    标签: .net vb.net generics


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        • 2013-08-13
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        相关资源
        最近更新 更多