检查Genric类型

时间:2017-10-17 10:06:46

标签: vb.net generics

如何测试泛型类的类型是否实现特定接口?

样品:

    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

如何做到这一点?还有另一种方法吗?

1 个答案:

答案 0 :(得分: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