从全名创建C#类型 [英] Creating C# Type from full name
问题描述
我正在尝试从以下类型的全名中获取Type对象:
I'm trying to get a Type object from type full name i'm doing the folowing:
Assembly asm = Assembly.GetEntryAssembly();
string toNativeTypeName="any type full name";
Type t = asm.GetType(toNativeTypeName);
我为空,为什么?
程序集是我的可执行文件(.net可执行文件),类型名称是:System.Xml.XmlNode
the assembly is my executable (.net executable) and the type name is: System.Xml.XmlNode
推荐答案
好吧,如果这确实是类型的全名(即包括名称空间)并且在该程序集中,则它应该可以工作.你能举个例子吗?当您使用Assembly.GetType
而不是Type.GetType
时,您不应在类型名称中包含程序集名称.
Well, if that really is the type's full name (i.e. including namespace) and it's in that assembly, then it should work. Could you give an example where it doesn't? As you're using Assembly.GetType
rather than Type.GetType
you shouldn't include the assembly name in the type name.
请注意,泛型类型的名称并非您所期望的那样.例如,您将使用:
Note that the name for a generic type isn't what you might expect it to be. For instance, you'd use:
assembly.GetType("System.Collections.Generic.List`1");
获取通用列表类型,然后使用Type.MakeGenericType
提供类型参数.
to get the generic list type, then use Type.MakeGenericType
to provide type arguments.
当然,这仅在类型为泛型时才有意义.如果那不是问题,我会仔细检查类型是否确实在您的输入程序集中.
Of course, that's only relevant when the type is generic. If that's not the problem, I'd double check that the type really is in your entry assembly.
哦,请注意,如果相关的话,嵌套类型将是"Container + Nested"而不是"Container.Nested".
Oh, and be aware that nested types will be "Container+Nested" rather than "Container.Nested" if that's relevant...
这篇关于从全名创建C#类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!