我有一些用于创建程序的数据。出于示例的目的,这是生成的代码:
using System;
namespace MyNamespace {
public class BuiltProgram{
public bool Eval(int x, int y, int z, out int ret) {
Console.WriteLine("Test");
ret = x + y + z;
return true;
}
}
}
我用来生成它的代码如下:
var factory = new ProgramFactory(tree);
var newProgram = factory.GetCompiledProgram();
// Program parsing code...
SyntaxTree programSyntaxTree = SyntaxTree.ParseText(newProgram);
var outputFile = "Compiled.dll";
var compilation = Compilation.Create(outputFile,
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { programSyntaxTree }
);
FileStream file;
using (file = new FileStream(outputFile, FileMode.Create)) {
EmitResult result = compilation.Emit(file);
}
// THIS CODE BREAKS:
Assembly assembly = Assembly.LoadFile(file.Name);
Type type = assembly.GetType("BuiltProgram");
var obj = Activator.CreateInstance(type);
int ret = 0;
type.InvokeMember("Eval",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
args: new[] {
(object)5,
(object)10,
(object)2,
ret
}
);
它在装配线上断开,因为它说它没有程序集清单,但我查看了“Compiled.dll”并且其中没有数据。我做错了什么?
答案 0 :(得分:1)
您必须添加对mscorlib的引用。
这将使其有效:
var compilation = Compilation.Create(outputFile,
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { programSyntaxTree },
references: new [] { new MetadataFileReference(typeof(object).Assembly.Location) }
);
访问您的类型时,还要添加名称空间。
Type type = assembly.GetType("MyNamespace.BuiltProgram");
您可能难以获得参数值。请参阅this。