Mono.Cecil TypeReference to Type?

时间:2010-11-15 12:38:40

标签: c# mono mono.cecil

无论如何都要从Mono.Cecil中的TypeReference转到Type?

2 个答案:

答案 0 :(得分:20)

就“框中的内容”而言,您只能使用ModuleDefinition.Import API反过来。

要从TypeReference转到System.Type,您需要使用反射和AssemblyQualifiedName手动查找。请注意,Cecil使用IL约定来转义嵌套类等,因此您需要应用一些手动更正。

如果你只想解决非通用的非嵌套类型,你应该没问题。

要从TypeReference转到TypeDefition(如果这就是您的意思),您需要TypeReference.Resolve();


请求的代码示例:

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

反思中使用的约定解释为here,对于Cecil约定,请参阅Cecil源代码。

答案 1 :(得分:2)

对于泛型类型,你需要这样的东西:

    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;
    }

请注意,此代码不处理嵌套类型,请查看@JohannesRudolph的答案

相关问题