Is there anyways to go from a TypeReference in Mono.Cecil to a Type?
In terms of "what's in the box" you can only have it the other way round, using the ModuleDefinition.Import
API.
To go from a TypeReference
to a System.Type
you will need to manually look it up using Reflection and the AssemblyQualifiedName
. Be aware that Cecil uses IL conventions to escape nested classes etc, so you need to apply some manual correction.
If you only want to resolve non-generic, non-nested types you should be fine though.
To go from a TypeReference
to a TypeDefition
(if that's what you meant) you need to to TypeReference.Resolve();
Requested Code Sample:
TypeReference tr = ... Type.GetType(tr.FullName + ", " + tr.Module.Assembly.FullName); // will look up in all assemnblies loaded into the current appDomain and fire the AppDomain.Resolve event if no Type could be found
The conventions used in Reflection are explained here, for Cecils conventions consult the Cecil Source Code.
For generic types you need something like this:
public static Type GetMonoType(this TypeReference type) { return Type.GetType(type.GetReflectionName(), true); } private static string GetReflectionName(this TypeReference type) { if (type.IsGenericInstance) { var genericInstance = (GenericInstanceType)type; return string.Format("{0}.{1}[{2}]", genericInstance.Namespace, type.Name, String.Join(",", genericInstance.GenericArguments.Select(p => p.GetReflectionName()).ToArray())); } return type.FullName; }
Please note this code doesn't handle nested types, please check @JohannesRudolph answer for this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With