是! 使用在Microsoft.CSharp,System.CodeDom.Compiler和System.Reflection命名空间中找到的方法。这是一个简单的控制台应用程序,它使用一个方法(“
Add42”)编译一个类(“
SomeClass”),然后允许您调用该方法。这是一个简单的示例,我对其进行了格式化,以防止滚动条出现在代码显示中。这只是为了演示在运行时编译和使用新代码。
using Microsoft.CSharp;using System;using System.CodeDom.Compiler;using System.Reflection;namespace RuntimeCompilationTest { class Program { static void Main(string[] args) { string sourceCode = @" public class SomeClass { public int Add42 (int parameter) { return parameter += 42; } }"; var compParms = new CompilerParameters{ GenerateExecutable = false, GenerateInMemory = true }; var csProvider = new CSharpCodeProvider(); CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms, sourceCode); object typeInstance = compilerResults.CompiledAssembly.CreateInstance("SomeClass"); MethodInfo mi = typeInstance.GetType().GetMethod("Add42"); int methodOutput = (int)mi.Invoke(typeInstance, new object[] { 1 }); Console.WriteLine(methodOutput); Console.ReadLine(); } }}


