如何获取传递给函数的匿名类型的对象类型而不创建该对象的实例

时间:2014-07-22 21:45:25

标签: .net vb.net object types anonymous-types

我知道我可以通过这种方式获得传递对象类型的类型

Public Function ConvertToValidationDataModel(Of T)(ByVal oSourceObject As Object) As Object
        Dim oDestinationObject As Object
        Dim oDestinationObjectType As Type

        oDestinationObject = Activator.CreateInstance(Of T)()

        oDestinationObjectType = oDestinationObject.GetType() 

End Function

但有没有办法在没有创建对象实例的情况下获得类型?

其他词 - 有这样的东西吗?

Dim oType AS Type = GetType(Of T)

1 个答案:

答案 0 :(得分:1)

您已经拥有该类型,它是通用参数T.以下是一个小型控制台应用及其输出:

http://grab.by/yO2S

Module Module1
Sub Main()
    Foo(Of Integer)(1)
    Foo(Of String)(1)

    Console.WriteLine()
    Console.WriteLine(Foo(Of Boolean)(True))

    Console.ReadLine()
End Sub

Public Function Foo(Of T)(ByVal oSourceObject As Object) As Type
    If TypeOf oSourceObject Is T Then
        Console.WriteLine("Types match.")
    Else
        Console.WriteLine("Types mismatch.")
    End If

    Return GetType(T)
End Function
End Module