LINQPad如何编译代码?
我猜它既不调用 csc.exe 也不实现整个编译器,那么它是如何工作的呢?
更新:感谢 Jon Skeet 提供了易于学习的代码。
string c = @"
public class A
{
public static void Main(string[] args)
{
System.Console.WriteLine(""hello world"");
}
}
";
CodeDomProvider compiler = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.WarningLevel = 4;
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults r = compiler.CompileAssemblyFromSource(parameters, c);
Assembly a = r.CompiledAssembly;
Type[] ts = a.GetTypes();
Type t = ts[0];
object o = t.GetMethod("Main").Invoke(null, new object[] { new string[] { } });
I am guessing it neither invokes csc.exe or implement an entire compiler, so how does it work?
Update: Thanks to Jon Skeet for the pointer to code that was easy to learn from.
string c = @"
public class A
{
public static void Main(string[] args)
{
System.Console.WriteLine(""hello world"");
}
}
";
CodeDomProvider compiler = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.WarningLevel = 4;
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults r = compiler.CompileAssemblyFromSource(parameters, c);
Assembly a = r.CompiledAssembly;
Type[] ts = a.GetTypes();
Type t = ts[0];
object o = t.GetMethod("Main").Invoke(null, new object[] { new string[] { } });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自“LINQPad 的工作原理”:
,显然还有更多内容,但这就是您询问的内容 - 请阅读链接以获取更多详细信息。
如果您想查看更简单的实现,您可以下载 Snippy 的源代码,我为 C# In Depth 创建的小工具。同样,它使用
CSharpCodeProvider
- 这是一个足够简单的示例,如果幸运的话,很容易理解。 (仅涉及几个类,IIRC。)From "How LINQPad Works":
Obviously there's rather more to it, but that's the bit you asked about - read the link for more details.
If you want to have a look at a rather more simplistic implementation, you could download the source code for Snippy, the little tool I created for C# in Depth. Again, it uses
CSharpCodeProvider
- and it's a simple enough example that it's easy to understand, with any luck. (There are only a few classes involved, IIRC.)乔恩大约 5 年前的回答现在已经过时了。
来自“LINQPad 的工作原理”(截至 2016 年 1 月 29 日):
您可以在此处查看如何使用 Roslyn 编译代码的示例:
立即学习 Roslyn - 第 16 部分- 发出API
Jon's answer from almost 5 years ago is now out of date.
From "How LINQPad Works" (as at 29 Jan 2016):
You can see an example of how to use Roslyn to compile your code here:
Learn Roslyn Now - Part 16 - The Emit API