Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono.Cecil TypeReference to Type?

Tags:

Is there anyways to go from a TypeReference in Mono.Cecil to a Type?

like image 950
Will Avatar asked Nov 15 '10 12:11

Will


2 Answers

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.

like image 111
Johannes Rudolph Avatar answered Sep 28 '22 08:09

Johannes Rudolph


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

like image 30
Andriy Tylychko Avatar answered Sep 28 '22 10:09

Andriy Tylychko