首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mono.Cecil TypeReference to Type?

Mono.Cecil TypeReference to Type?
EN

Stack Overflow用户
提问于 2010-11-15 20:38:40
回答 2查看 8.8K关注 0票数 23

有什么方法可以从Mono.Cecil中的TypeReference转换为类型吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-15 20:47:29

就“盒子里有什么”而言,只能反过来使用ModuleDefinition.Import应用编程接口。

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

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

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

请求的代码示例:

代码语言:javascript
复制
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源代码。

票数 24
EN

Stack Overflow用户

发布于 2014-07-29 20:52:51

对于泛型类型,您需要类似以下内容:

代码语言:javascript
复制
    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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4184384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档