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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2396861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:45:24  来源:igfitidea点击:

Create a new instance of a type given as parameter

vb.net

提问by stex

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

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

I thought of something like the following:

我想到了以下内容:

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

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)

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

Thanks in advance!

提前致谢!

回答by JDC

Personaly I like this syntax much more.

我个人更喜欢这种语法。

Public Class Test(Of T As {New})
    Public Shared Function GetInstance() As T
        Return New T
    End Function
End Class

Or if you want to limit the possible types:

或者,如果您想限制可能的类型:

Public Class Test(Of T As {New, MyObjectBase})
    Public Shared Function GetInstance() As T
        Return New T
    End Function
End Class

回答by M.A. Hanin

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

Using a type parameter:

使用类型参数:

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