Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - How does LINQPad compile code?

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[] { } });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From "How LINQPad Works":

LINQPad compiles your queries using .NET's CSharpCodeProvider (or VBCodeProvider)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...