0

我有一些用于创建程序的数据。出于示例的目的,这是生成的代码:

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”并且其中没有数据。我究竟做错了什么?

4

1 回答 1

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");

您可能难以获得参数值。看到这个

于 2013-07-07T01:13:36.063 回答