Compile and run dynamic code, without generating EXE?

后端 未结 8 1868
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 14:17

I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.

Basical

8条回答
  •  情歌与酒
    2020-11-27 14:29

    using (Microsoft.CSharp.CSharpCodeProvider foo = 
               new Microsoft.CSharp.CSharpCodeProvider())
    {
        var res = foo.CompileAssemblyFromSource(
            new System.CodeDom.Compiler.CompilerParameters() 
            {  
                GenerateInMemory = true 
            }, 
            "public class FooClass { public string Execute() { return \"output!\";}}"
        );
    
        var type = res.CompiledAssembly.GetType("FooClass");
    
        var obj = Activator.CreateInstance(type);
    
        var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
    }
    

    This compiles a simple class from the source code string included, then instantiates the class and reflectively invokes a function on it.

提交回复
热议问题