代码之家  ›  专栏  ›  技术社区  ›  Fxbrandon

.NET返回值的类型

  •  0
  • Fxbrandon  · 技术社区  · 9 年前

    似乎是一个模棱两可的问题,但问题是我有这样的想法:

    Dim a As MyObject
    a = GetData(a.GetType) 
    
    Function GetData(tp as Type)
         DotheWork(tp)
    End Function
    

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

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

    1 回复  |  直到 9 年前
        1
  •  2
  •   Jürgen Steinblock    9 年前

    这是不可能的,因为 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,并且函数没有返回任何结果 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
    
    推荐文章