使用 CodeDom 将一种语言转换为另一种语言?
您可以运行我的源代码作为示例 http://www.pastie.org/1969780
我基本上采用了这个并使用它 http://msdn.microsoft.com/en-us/library/ms404245.aspx
如果我构建一个像msdn链接所示的codedom,我可以生成cs和vb代码。但是,如果我读回 cs 或 vb 代码并尝试生成其他语言的源代码,我只会得到我最初读取的任何代码(您将在 vb 文件中看到 cs 代码,反之亦然)。
如何从一种语言读取源代码并将其生成为另一种语言?
You can run my source as an example http://www.pastie.org/1969780
I essentially took this and played around with it http://msdn.microsoft.com/en-us/library/ms404245.aspx
If i build a codedom like the msdn link shows i can generate cs and vb code. However if i read cs or vb code back and try to generate the source in the other language i just get whatever code i originally read from (you'll see cs code in the vb file and vice versa).
How do i read in source from one language and generate it to another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照示例中所示的方式执行此操作不起作用,因为您使用的是
CodeSnippetCompileUnit
。本质上,它只包含一个成员Value
,它逐字包含您的原始代码。现在,CodeDomProvider/CodeDomGenerator 并不那么智能,它不会在内部将逐字源代码解析为 CodeDom 树,然后将其吐出为您想要的语言。事实上,使用 dotPeak 或其他东西,您可以看到,在使用 CodeSnippetCompileUnit 的情况下,它只会输出 Value-Member 的原始内容。
您需要做的是从读入的源代码手动创建一个 CodeDom 树,使用您选择的语言的代码生成器并将其作为源代码写出来。
坦率地说,我不知道 System.CodeDom 是否提供了这种努力的基础设施(即您需要的每种源语言的解析器,它输出 CodeDom 树)。此外,我不知道这是否真的是最好的方法。其他方法可能包括将源代码编译为(至少是 IL)并将其转换回目标语言(很像反编译器) - 当然,使用这种方法您会丢失(至少)原始源中的注释。
Doing it how you showed in your example does not work, because you are using a
CodeSnippetCompileUnit
. That essentially, just contains one member,Value
, which contains your original code verbatim.Now, the CodeDomProvider/CodeDomGenerator is not that smart, it will not internally parse that verbatim source code into a CodeDom tree that it then spits out as the language you want. In fact, using dotPeak or whatever, you can see that in case of using a CodeSnippetCompileUnit it will just output the original content of the Value-Member.
What you need to do is to manually create a CodeDom tree from the read-in source code, feat that the the code generator of the language of your choice and write it out as source.
Frankly, I don't know if the infrastructure for such an endeavor is provided by
System.CodeDom
(namely a parser for each source language you need, that outputs a CodeDom tree). Further, I don't know if that is actually the best way to do it anyway. Other approaches could include compiling the source to (at least IL) and convert that back to the target language (much like a decompiler) - of course using that approach you loose (at least) comments from the original source.