2017-10-17 86 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

感谢很多:) –