How to get the type for a class by sending just the name of the class instead of the class itself as the parameter?

我怕爱的太早我们不能终老 提交于 2019-12-10 09:57:03

问题


Dim a as Type=GetType(className) would gimme the type. But I have only the name of the class as string. I want something like GetType("class1") which would return the type.


回答1:


Type.GetType("class1")



回答2:


Both Type.GetType(...) and Assembly.GetType(...) expects a fully qualified type name. Thus, only passing in the class name without its namespace will not yield the Type.

If you make sure to include the namespace like this:

Type.GetType("Fully.Qualified.Namespace.class1")

will yield the same result as GetType(class1).

Update: if you don't know the namespace of your class, you could do a search (using Linq mind you) on types in the current assembly:

GetType().Assembly.GetTypes().First(type => type.Name == "AssemblyModuleTests")

I assume this is a slower operation than looking up types using fully qualified names since GetTypes() enumerates all types in the assembly.



来源:https://stackoverflow.com/questions/1411372/how-to-get-the-type-for-a-class-by-sending-just-the-name-of-the-class-instead-of

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