【发布时间】:2014-08-26 09:47:38
【问题描述】:
对于脚本引擎,我尝试将 C# 集成到 F# Interactive 中,以便我可以在 F# Interactive 中声明 C# 类。我已经设法使用 Microsoft CSharp Code Provider 将 C# 代码编译为 System.Reflection.Assembly 对象(如果您对此感兴趣,请参见下文)。 所以假设脚本是一个 System.Reflection.Assembly。 使用
script.GetTypes()
我可以获得脚本中声明的所有类型的类型信息,例如如果我的 脚本在以下 C# 代码中声明:
let CS_code="""
namespace ScriptNS
{
public class Test
{
public string AString()
{
return "Test";
}
}
}"""
script.GetTypes 将包含 ScriptNS.Test 类的类型信息。 我想要实现的是像 F# Interactive 中的任何其他类一样使用这个类,例如
let t=new ScriptNS.Test()
因此,我的问题是:我可以以某种方式将类导入 FSI AppDomain 吗?
感谢您的帮助,
安德烈亚斯
附:我发现的一种可能性是使用 #r 指令。一个可行的解决方案是:
open System.Reflection
open System.CodeDom.Compiler
// Create a code provider
let csProvider=new Microsoft.CSharp.CSharpCodeProvider()
// Setup compile options
let options=new CompilerParameters()
options.GenerateExecutable<-false
options.GenerateInMemory<-false
let tempfile="c:\Temp\foo.dll"
options.OutputAssembly<-tempfile
let result=csProvider.CompileAssemblyFromSource(options,CS_code)
let script=result.CompiledAssembly
#r "c:\Temp\foo.dll"
// use the type
let t=new ScriptNS.Test()
但是,我对额外的 dll 不满意。
【问题讨论】:
标签: c# reflection f# f#-interactive