2017-10-17 77 views
0

如何測試泛型類的類型是否實現特定的接口?檢查Genric類型

樣本:

Public Interface IBaseItemInterface(of Type) 
    ... 
    End Interface 

    Public Interface ISpecificItemInterface(Of Type) 
     Inherits IBaseItemInterface(of Type) 
    ... 
    End Interface 

    Public Interface IRootInterface(of Type, TEntity as IBaseItemInterface)) 
    ... 
    End Interface 

    'Implementation 
    Public Class Sample(of Type, TEntity as IBaseItemInterface)) 
     Implements IRootInterface(of Type, TEntity) 

     Public Sub test() 
      **If TEntity Implements ISpecificItemInterface then** 
       DoSomethingSpecific 
      End if 
     End Sub 
    End Class 

如何才能做到這一點?有沒有另一種方法來做到這一點?

回答

0

可以使用...

Public Sub Test() 
    Dim type = GetType(TEntity) 
    Dim isMySpecificInterface = type.IsGenericType AndAlso 
      type.GetGenericTypeDefinition() Is GetType(ISpecificItemInterface(Of)) 

    If isMySpecificInterface then 
     ' DoSomethingSpecific 
    End if 
End Sub 
+0

感謝很多:) –