2015-02-05 93 views
1

我想找一個使用C#編譯CompilerAssemblyFromSource的F#代碼的工作示例。在我目前的嘗試中,我無法創建編譯器,得到「NotSupportedException」異常,「編譯不支持」消息。我的猜測是我只是做錯了,因爲F#交互式工作,並且必須做類似的事情,但要正確。從C#執行F#源代碼

// C# 
var source = "let add x y = x + y"; 
var cleanProvider = new FSharp.Compiler.CodeDom.FSharpCleanCodeProvider(); 
var compilerParams = new System.CodeDom.Compiler.CompilerParameters(); 
const string outfile = "C:\\temp\\FSFoo.EXE"; 
compilerParams.OutputAssembly = outfile; 
compilerParams.GenerateExecutable = true; 

var compiler = cleanProvider.CreateCompiler(); 
var compilerResults = compiler.CompileAssemblyFromSource(compilerParams, source); 
var results = cleanProvider.CompileAssemblyFromSource(compilerParams, source); 

回答

4

獨此代碼將編譯你想要什麼,還有留在額外的診斷/調試代碼

using FSharp.Compiler.CodeDom; 
using System.CodeDom; 
var codeString = "let add x y = x + y"; 
var provider = new FSharp.Compiler.CodeDom.FSharpCodeProvider(); 
Environment.CurrentDirectory.Dump("exe is going here"); // diagnostic helper 
var targetFile = "FSFoo.exe"; 
provider .CompileAssemblyFromSource(new System.CodeDom.Compiler.CompilerParameters(){ OutputAssembly= targetFile, GenerateExecutable=true }, new []{codeString}).Dump(); // .Dump is just for diagnostics, remove if you aren't running this in linqpad 
if(!System.IO.File.Exists(targetFile)){ 
    throw new FileNotFoundException("Could not find compiled exe",targetFile); 
} 

System.IO.Directory.GetFiles(Environment.CurrentDirectory,"FSFoo.exe").Dump();// .Dump is just for diagnostics, remove if you aren't running this in linqpad 

其他資源,可以幫助:

http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm

"CompileAssemblyFromSource" in f# powerPack codeDom

http://tiku.io/questions/638972/run-f-code-on-server-even-when-f-is-not-installed-there