我可以从PowerShell执行C#源代码,从C#执行PowerShell源代码。 问题是,如何在不编译csc.exe的情况下从C#程序执行C#源?
答案 0 :(得分:2)
是。使用CodeDom类命名空间在.net框架中明确地提供了这一功能。 http://msdn.microsoft.com/en-us/library/650ax5cx(v=vs.110).aspx System.CodeDom和System.CodeDom.Compiler。
(来自文件)
CSharpCodeProvider provider = new CSharpCodeProvider();
// Build the parameters for source compilation.
CompilerParameters cp = new CompilerParameters();
// Add an assembly reference.
cp.ReferencedAssemblies.Add( "System.dll" );
// Generate an executable instead of
// a class library.
cp.GenerateExecutable = true;
// Set the assembly file name to generate.
cp.OutputAssembly = exeFile;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);
我意识到这确实在内部使用了编译器,这是OP希望避免的,但我看不出有任何理由不使用它。