23

无论如何从 Mono.Cecil 中的 TypeReference 到 Type 吗?

4

2 回答 2

24

就“盒子里有什么”而言,您只能使用ModuleDefinition.Import API 反其道而行之。

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

如果您只想解析非泛型、非嵌套类型,那么您应该没问题。

要从 aTypeReference变为 a 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

此处解释了反射中使用的约定,对于 Cecils 约定,请参阅 Cecil 源代码。

于 2010-11-15T12:47:29.163 回答
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 对此的回答

于 2014-07-29T12:52:50.600 回答