[ACCEPTED]-Mono.Cecil TypeReference to Type?-mono.cecil

Accepted answer
Score: 24

In terms of "what's in the box" you 12 can only have it the other way round, using 11 the ModuleDefinition.Import API.

To go from a TypeReference to a System.Type you will 10 need to manually look it up using Reflection 9 and the AssemblyQualifiedName. Be aware that Cecil uses IL conventions 8 to escape nested classes etc, so you need 7 to apply some manual correction.

If you only 6 want to resolve non-generic, non-nested 5 types you should be fine though.

To go from 4 a TypeReference to a TypeDefition (if that's what you meant) you 3 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 2 used in Reflection are explained here, for Cecils 1 conventions consult the Cecil Source Code.

Score: 2

For generic types you need something like 3 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 2 nested types, please check @JohannesRudolph 1 answer for this

More Related questions