Create an object from another objects type

有些话、适合烂在心里 提交于 2019-12-10 10:04:05

问题


In Visual Basic.net, can I create an Object, or a List of T with the type from another object.

Here is some code:

Dim TestObjectType As Author
Dim TestObject As TestObjectType.GetType

I am getting an error:

TestObjectType.GetType is not defined

EDIT

Can I create a Type object of a certain type, and then create objects, lists or cast objects to this type from this Type object?


回答1:


Dim TestObject As TestObjectType.GetType will look for a type named GetType in the namespace TestObjectType.


To create an instance of a class using System.Type, you can use Activator.CreateInstance:

Dim TestObject = Activator.CreateInstance(TestObjectType.GetType())

To create a generic list, you can use Type.MakeGenericType:

Dim listType = GetType(List(Of )).MakeGenericType(TestObjectType.GetType())
Dim list = Activator.CreateInstance(listType)

Note that both snippets above return an Object; however, you can make use of generics to achieve compile time safety:

Dim TestObject = CreateNew(TestObjectType)
Dim AuthorList = CreateNewList(TestObjectType)

...

Function CreateNew(Of T As New)(obj As T) As T 
    Return New T()
End Function

Function CreateNewList(Of T)(obj As T) As List(Of T)
    Return New List(Of T)
End Function


来源:https://stackoverflow.com/questions/19110559/create-an-object-from-another-objects-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!