在c#中编译/序列化一段代码

时间:2016-10-13 12:37:36

标签: c# reflection roslyn

我的目标是编写一个可以编译/序列化任何代码的类。我正在考虑一些想法,它只是一个概念,我不指望你编写完整的解决方案,我正在考虑最好的方法来做到这一点。 我想到了两个想法:

  1. 在编译器类中创建一个接口,然后读取接口方法体并使用roslyn将其编译为单独的程序集。
  2. 序列化表达式树。
  3. AD 1.第一个概念

    public class Runnable : IRunnable
    {
        void Run();
    }
    
    public interface ICodeRunner
    {
        void RunCode<T>() where T : IRunnable
    }
    
    public class CodeRunner : ICodeRunner
    {
        public void RunCode<T>() where T : IRunnable
        {
            MethodInfo mi = typeof(T).GetMethod("Run");
            MethodBody mb = mi.GetMethodBody();
            // somehow get method body if possible and compile it using roslyn.
            // like this:
            // string syntaxTree = mb.GetMethodBodyToString() // this method doesn't exist. There must be a way to do that
            // CSharpCompilation compilation = CSharpCompilation.Create(
            //    "abc",
            //    new[] { syntaxTree },
            //    new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) },
            //    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
    
            // using (var dllStream = new FileStream(@"abc.dll", FileMode.OpenOrCreate))
            // using (var pdbStream = new FileStream(@"abc.pdb", FileMode.OpenOrCreate))
            // {
            //    var emitResult = compilation.Emit(dllStream, pdbStream);
            //    if (!emitResult.Success)
            //    {
            //        // emitResult.Diagnostics
            //    }
            // }
        }
    }
    

    另一种方法是将lambda序列化为表达式树到文件中,我看到有些库可以做到这一点 有没有更简单的方法呢?

    我的一般用例是创建一个类,它可以将一些代码(逻辑)和有效负载序列化为两个单独的文件,通过线路发送它并在另一台机器上运行一段代码+有效负载。接口是exe文件和输入文件,通过线路发送。这个问题有没有现成的解决方案?

0 个答案:

没有答案