如何使用 Roslyn 加载现有程序集,对其进行转换并生成新的 .cs 文件 [英] How to load an existing assembly with Roslyn, transform it and generate new .cs files

查看:27
本文介绍了如何使用 Roslyn 加载现有程序集,对其进行转换并生成新的 .cs 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Roslyn 的文档似乎有点缺乏?我找不到很好的综合文档.

It seems like the documentation around Roslyn is a bit lacking? I am not able to find good comprehensive documentation.

我基本上要做的是复制现有 API (.dll) 的公共表面转换成一个新的程序集(需要创建源代码 .cs 文件!),同时对生成的代码进行各种转换(想想制作包装类).

What I am trying to do essentially is copy the public surface of an existing API (.dll) into a new assembly (need to create source code .cs files!) and at the same time make a variety of tranformations to the resulting code (think making wrapper classes).

非常感谢我如何使用 Rolsyn 从现有程序集中加载初始 SyntaxTree 以及如何进行这些基本转换(例如排除内部类等)

Would really appreciate any help in how I can use Rolsyn to load the initial SyntaxTree from an existing assembly and how to do those basic tranforms (for example exclude internal classes etc)

推荐答案

在当前的 Roslyn CTP 中,有一个 Roslyn.Services.MetadataAsSource 命名空间,可用于将类型的公共接口转换为源代码.这就是我们实现 F12元数据作为源"功能的原因.现在,它只生成一个实际上不会编译的源代码外壳,因此您必须使用更多的 API 将语法树修改为您想要的.或者,您可以使用 Roslyn.Services.CodeGeneration 命名空间自动从这些符号生成源代码.我应该警告 MetadataAsSource 命名空间可能会在 API 的未来版本中消失.

In the current Roslyn CTP there is a Roslyn.Services.MetadataAsSource namespace which can be used to convert an type's public interface to source code. This is what we implement the F12 "metadata as source" feature with. Now, it generates only a shell of source code which won't actually compile, so you'd have to use further APIs to munge the syntax tree into what you want. Alternatively, you could use the Roslyn.Services.CodeGeneration namespace to generate source from these symbols automatically. I should warn the MetadataAsSource namespace may go away in future versions of the API.

您可以通过创建一个包含您关心的元数据引用的空编译来从元数据导入符号,然后从该编译浏览 GlobalNamespace 属性的类型层次结构,或调用 Compilation.GetReferencedAssemblySymbol() 然后深入研究.这实际上比使用反射要好得多,因为它会从C# 透视图"而不是CLR 透视图"正确表达符号模型——反射不会为您提供 dynamic、一些默认参数值等

You can import symbols from metadata by creating an otherwise empty compilation with the metadata references you care about added, and then from that compilation browsing the type hierarchy from GlobalNamespace property, or calling Compilation.GetReferencedAssemblySymbol() and then digging through that. This is actually far better than using reflection, since it'll properly express the symbol model from the "C# perspective" instead of the "CLR perspective" -- reflection won't give you information for uses of dynamic, some default parameter values, etc.

这篇关于如何使用 Roslyn 加载现有程序集,对其进行转换并生成新的 .cs 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆