是否可以在不编译的情况下调用 C# 词法/语法分析器?
Considering this question of SO, where whole C# in-memory compiler is being called. When only lexical and syntactic analyzing is required: parse text as a stream of lexemes, check them and exit.
Is it possible in current version of System.CodeDom.Compiler, if not - will it be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以使用 Mono,我相信它有一个 C# 解析器/词法分析器,您可能会能够使用。
这是一个可以查看的链接。至于 MS C# 团队计划做什么,有人在谈论在某个时候将 C# 编译器变成一项“服务” - 但尚不清楚这意味着什么或何时会发生。
If you can use Mono, I believe it has a C# parser/lexer you may be able to use.
Here's a link to look into. As for what the MS C# team is planning to do, there is some talk of at some point making the C# compiler into a "service" - but it's unclear what that means or when that will happen.
虽然看起来代码是在内存中编译的 (CompilerParameters.GenerateInMemory),但实际情况并非如此。使用与 Visual Studio 中使用的相同的编译器来编译代码 (csc.exe)。它由 CreateProcess(很像 Process.Start)启动,并在进程外运行,将代码编译到磁盘上临时文件夹中的程序集。该GenerateInMemory选项调用Assembly.LoadFrom()来加载程序集。
只需将GenerateInMemory 设置为false,并在完成后删除OutputAssembly,即可获得相当于语法检查的效果。
虽然这听起来有点倒退,但它的巨大好处是,这不会给您的进程带来任何内存压力。这将帮助您直到 C# 5.0 发布。
While it might look like the code is compiled in-memory (CompilerParameters.GenerateInMemory), that's not what actually happens. The same compiler as the one used in Visual Studio is used to compile the code (csc.exe). It gets started by CreateProcess (much like Process.Start) and runs out-of-process to compile the code to an assembly on disk in a temporary folder. The GenerateInMemory option invokes Assembly.LoadFrom() to load the assembly.
You'll get the equivalent of a syntax check simply by setting GenerateInMemory to false and delete the OutputAssembly after it is done.
While this might sound kinda backwards, the huge benefit it has is that this won't put any memory pressure on your process. This will hold you over until C# 5.0 ships.