Use CodeDom to convert one language to another?
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?
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.
精彩评论