c# - 如何从与C#中的System不同的命名空间获取类型? [英] How to get type from different namespace than System in c#?
问题描述
我想在获得仅字符串名称时创建类型.这里很明显:
I would like to create types when being given only strings of their names. Here it's obvious:
Type t = System.Type.GetType("System.Double");
但是当我尝试从另一个命名空间获取类型时,例如 System.Drawing
,上述方法不会返回正确的类型.我找到的工作解决方案:
But when I try to get type from another namespace, like System.Drawing
, the above method won't return the correct type. Working solution I've found:
Assembly foundAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(assembly => assembly.GetName().Name == "System.Drawing");
Type t = foundAssembly.GetType("System.Drawing.Color");
但是,它看起来很纯粹,我想这样做会花费一些时间(在我的情况下,AppDomain.CurrentDomain
有 22 个程序集,但乘以 10000,就可以了).那么我们可以更快地得到它吗?我不是在寻找像 type = typeof(System.Drawing.Color);
这样的解决方案,因为可能我必须翻译 "System.Text.StringBuilder"
到它的类型等等...
However, it looks pure and I guess doing it costs some time (AppDomain.CurrentDomain
has 22 assemblies in my case, but multiplied by 10000, it's something). So can we get it faster? I'm not searching for a solution like type = typeof(System.Drawing.Color);
, because possibly I'll have to translate "System.Text.StringBuilder"
to its type and so on...
推荐答案
如果你想让这个工作,你必须使用完全限定的类型名称(包括程序集).对于 System.Drawing.Color
这将是(对于 .Net 4.0):
If you want to make this work, you'll have to use the fully qualified type name (including the assembly). For System.Drawing.Color
that would be (for .Net 4.0):
System.Drawing.Color, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Type t = Type.GetType("System.Drawing.Color, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
要获取已加载类型的完全限定名称,请使用
to get the fully qualified name of an already loaded type, use
t.AssemblyQualifiedName
这篇关于c# - 如何从与C#中的System不同的命名空间获取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!