我已经搜索了一个答案并找到了一些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
Run Code Online (Sandbox Code Playgroud)
我知道,我可以使用Activator.Create ...方法创建一个新实例,但是如何创建这种类型的数组或者只是声明一个新变量?(暗淡)
提前致谢!
JDC*_*JDC 18
Personaly我更喜欢这种语法.
Public Class Test(Of T As {New})
Public Shared Function GetInstance() As T
Return New T
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
或者,如果您想限制可能的类型:
Public Class Test(Of T As {New, MyObjectBase})
Public Shared Function GetInstance() As T
Return New T
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
M.A*_*nin 17
这实际上取决于类型本身.如果类型是引用类型并且具有空构造函数(接受零参数的构造函数),则以下代码应创建它的一个内容:使用泛型:
Public Function f(Of T)() As T
Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {})
Return tmp
End Function
Run Code Online (Sandbox Code Playgroud)
使用类型参数:
Public Function f(ByVal t As System.Type) As Object
Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function
Run Code Online (Sandbox Code Playgroud)