加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net – 创建作为参数给定的类型的新实例

发布时间:2020-12-17 00:05:29 所属栏目:大数据 来源:网络整理
导读:我已经搜索了一个答案,发现了一些c#-examples,但无法在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)
我已经搜索了一个答案,发现了一些c#-examples,但无法在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 …方法创建一个新实例,但是如何创建这种类型的数组或只是声明一个新变量? (暗淡)

提前致谢!

这实际上取决于类型本身.如果类型是引用类型并且具有空构造函数(接受零参数的构造函数),则以下代码应创建它的内容:
使用泛型:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读