从另一个对象类型创建一个对象 [英] Create an object from another objects type

查看:72
本文介绍了从另一个对象类型创建一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Visual Basic.net 中,我可以创建一个对象,或一个来自另一个对象的类型的 T 列表.

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

这是一些代码:

Dim TestObjectType As Author
Dim TestObject As TestObjectType.GetType

我收到一个错误:

TestObjectType.GetType 未定义

TestObjectType.GetType is not defined

编辑

我可以创建某个类型的 Type 对象,然后从这个 Type 对象创建对象、列表或将对象强制转换为该类型吗?

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?

推荐答案

Dim TestObject As TestObjectType.GetType 将在命名空间 中查找名为 GetType 的类型测试对象类型.

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

要使用 System.Type 创建类的实例,您可以使用 Activator.CreateInstance:

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

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

要创建通用列表,您可以使用 Type.MakeGenericType:

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

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

注意上面的两个片段都返回一个Object;但是,您可以使用泛型来实现编译时安全:

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

这篇关于从另一个对象类型创建一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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