【问题标题】:.NET Type of return value.NET 返回值类型
【发布时间】:2015-09-02 20:54:56
【问题描述】:

似乎是一个模棱两可的问题,但问题是我有类似的东西:

Dim a As MyObject
a = GetData(a.GetType) 

Function GetData(tp as Type)
     DotheWork(tp)
End Function

所以,我想知道是否有任何方法可以省略 GetData() 中的 Type 参数并从赋值左侧的变量中获取它。 (基本上是因为我在 GetData() 中使用了反射,所以我需要一个参数类型的实例)

这可能吗???非常感谢!

【问题讨论】:

  • 我已经删除了 C# 标签,因为这似乎更多地是关于 vb.net 语法而不是 .net
  • 你应该先打开Option Strict

标签: .net vb.net system.reflection


【解决方案1】:

这是不可能的,因为GetData() 是在分配之前评估的。您可以做的是通用方法:

dim a as MyObject = GetData(of MyObject)()

Function GetData(Of T)()
    Dim _t As Type = GetType(T)
    DotheWork(_t)
End Function

我就是这样做的。

请注意,初始代码中的 a.GetType 将失败,因为 a 是 Nothing 并且您的函数不会返回任何内容,因此在 GetData() 之后也不会为 a 分配任何内容。

也许你想实现这样的目标:

Function GetData(Of T As { IMyType, New })()

    Dim instance As T = Activator.CreateInstance(Of T)()
    DotheWork(instance)
    Return instance

End Function

Function DotheWork(instance As IMyType)
    instance.Init()
End Function

Interface IMyType
    Sub Init()
End Interface

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多