检查泛型参数类型是否派生自某个类X.

时间:2016-04-03 07:29:59

标签: vb.net generics inheritance

检查类型参数是否类型(或派生自某些类型X)的正确方法是什么? E.g。

Function MyFunc(Of T As BaseClass)() As T
  If TypeOf T Is GetType(ChildClass1) Then
    'Do something specific to ChildClass1
  End If

  'Do things common to all BaseClass objects
End Function

无论是否有TypeOf,上述代码都无法编译。

1 个答案:

答案 0 :(得分:2)

TypeOf T替换为GetType(T) 您的代码应如下所示:

Function MyFunc(Of T As BaseClass)() As T
  If GetType(T) Is GetType(ChildClass1) Then
    'Do something specific to ChildClass1
  End If

  'Do things common to all BaseClass objects
End Function