在C#中实现动态代码执行的方法可以使用反射和编译器服务。以下是一种简单的方法:
使用CSharpCodeProvider类动态编译代码using System;using System.CodeDom.Compiler;using System.Reflection;public class DynamicCodeExecutor{ public static void Execute(string code) { var provider = new CSharpCodeProvider(); var parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { Console.WriteLine(error.ErrorText); } } else { Assembly assembly = results.CompiledAssembly; Type type = assembly.GetTypes()[0]; MethodInfo method = type.GetMethod("Execute"); method.Invoke(null, null); } }}使用反射执行动态编译后的代码public class DynamicCode{ public static void Execute() { Console.WriteLine("Dynamic code executed!"); }}调用Execute方法执行动态代码string code = @"using System;public class DynamicCode{ public static void Execute() { Console.WriteLine(""Dynamic code executed!""); }}";DynamicCodeExecutor.Execute(code);通过上述方法,可以动态编译并执行C#代码。请注意,动态执行代码可能存在安全风险,务必谨慎使用。