创建作为参数给出的类型的新实例 [英] Create a new instance of a type given as parameter

查看:25
本文介绍了创建作为参数给出的类型的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了一个答案并找到了一些 c# 示例,但无法在 vb.net 中运行:

I've searched for an answer and found some c#-examples, but could not get this running in vb.net:

我想到了以下内容:

public function f(ByVal t as System.Type)
  dim obj as t
  dim a(2) as t

  obj = new t
  obj.someProperty = 1
  a(0) = obj

  obj = new t
  obj.someProperty = 2
  a(1) = obj

  return a
End Function

我知道,我可以使用 Activator.Create... 方法创建一个新实例,但是如何创建此类型的数组或仅声明一个新变量?(昏暗)

I know, I can create a new instance with the Activator.Create... methods, but how to create an array of this type or just declare a new variable? (dim)

提前致谢!

推荐答案

这实际上取决于类型本身.如果类型是引用类型并且有一个空构造函数(一个接受零参数的构造函数),下面的代码应该创建它的一个实例:使用泛型:

It really depends on the type itself. If the type is a reference type and has an empty constructor (a constructor accepting zero arguments), the following code should create an insance of it: Using Generics:

Public Function f(Of T)() As T
    Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {})
    Return tmp
End Function

使用类型参数:

Public Function f(ByVal t As System.Type) As Object
    Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function

这篇关于创建作为参数给出的类型的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆