我有以下代码根据类名创建一个类的实例。
'Get a System.Type corresponding to the name of the parent class
Dim tt As Type = Type.GetType(item.ParentClass)
'Create an instance of the specified type using the types default constructor
Dim theObject As Object = Activator.CreateInstance(tt)
如果我在MainClassName.Namespace.ClassName
中拥有完整的课程,这样可以正常工作
但是,如果我尝试仅使用ClassName
执行此操作,则tt
等于零。
有没有办法使用ClassName
并获取MainClassName.Namespace.ClassName
答案 0 :(得分:0)
您需要使用Type.AssemblyQualifiedName,如下所示:
'part 1 of your code - store class name in a universal format
Dim className As String = GetType(item.ParentClass).AssemblyQualifiedName
'part 2 of your code - use a previously stored class name to create instance
Dim tt As Type = Type.GetType(className)
Dim theObject As Object = Activator.CreateInstance(tt)
归功于此answer on SO。
答案 1 :(得分:0)
有没有办法使用
中的完全限定名称ClassName
并获取MainClassName.Namespace.ClassName
没有。这在逻辑上是行不通的。请考虑以下情况:您有两个类Foo.X
和Bar.X
。因此,仅指定X
是不明确的。事实上,这首先是名称空间和完全限定名称背后的动机。
即使有可能(例如通过返回候选类型的 list ),这也是不切实际的,因为它需要运行时遍历所有引用加载的整个类列表。组件。这可以是巨大的数字,即使只加载了基本框架。 GetType
会非常低效。