泛型问题。我需要反思来回答这个问题吗?

时间:2011-03-31 18:20:42

标签: vb.net generics reflection

Public Class B

End Class


Public Class D

    Inherits B

End Class

Public Class SomeClass


    Public Shared Sub SomeFunction2(Of TGeneric As B)()

        'Is there a way that I can tell whether the the Type used
        'as TGeneric is of type "B" or "D" without having 
        'an instance of a class also passed in?
        'Reflection? How?

    End Sub

End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SomeClass.SomeFunction2(Of D)()

    End Sub
End Class

1 个答案:

答案 0 :(得分:4)

这取决于你的意思是“是B型还是D型”。

如果您只想区分实际调用SomeFunction2(Of B)SomeFunction2(Of AnyTypeThatInheritsFromB)的人,那么您可以这样做:

If GetType(B) Is GetType(TGeneric) Then
    ... they passed in B
Else
    ... they passed in a subclass
End If

但这似乎有点代码味道。泛型是为您而设的不关心实际类型是什么。你需要知道的原因是什么?