How to get type from different namespace than Syst

2019-08-26 22:18发布

问题:

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");

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");

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...

回答1:

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


回答2:

While the accepted solution properly answers the question, I would also recommend caching any of these conversions into a <string, Type> dictionary, where the string is the input you are parsing, and the Type is the result of the lookup. This should significantly improve your performance since reflection is slow.