【问题标题】:How To Get The Object Type Of The Anonymous Type Passed To The Function Without Creating An Instance Of That Object如何在不创建该对象的实例的情况下获取传递给函数的匿名类型的对象类型
【发布时间】:2014-09-13 22:12:09
【问题描述】:

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

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)

【问题讨论】:

  • 你不能调用GetType(T)吗?
  • 当我做 Dim oType As Type = GetType(OF T) 时,它会在 Of 下划线并说“关键字没有命名类型”
  • 再次阅读我的评论,它说 GetType(T) not GetType(Of T)
  • 谢谢您,先生!像魅力一样工作!解决了!

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多