Is it possible to dynamically compile and execute C# code fragments?

后端 未结 6 1741
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 07:10

I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would c

6条回答
  •  一整个雨季
    2020-11-21 07:37

    Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

            var refs = AppDomain.CurrentDomain.GetAssemblies();
            var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
            var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
            var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
            compileParams.GenerateInMemory = true;
            compileParams.GenerateExecutable = false;
    
            var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
            var asm = compilerResult.CompiledAssembly;
    

    In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

            var tempType = asm.GetType(className);
            var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);
    

    Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

提交回复
热议问题