c# 动态执行代码
时间: 2023-07-27 21:24:09 浏览: 228
C# 中可以使用动态编译的方式来执行代码。下面是一个简单的示例:
```csharp
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace DynamicCodeExecution
{
class Program
{
static void Main(string[] args)
{
// 定义要编译的代码
string code = @"
using System;
namespace DynamicCodeExecution
{
public class MyClass
{
public static void MyMethod()
{
Console.WriteLine(""Hello, world!"");
}
}
}
";
// 编译代码
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
// 获取编译后的程序集和类型
Assembly assembly = results.CompiledAssembly;
Type type = assembly.GetType("DynamicCodeExecution.MyClass");
// 调用方法
MethodInfo method = type.GetMethod("MyMethod");
method.Invoke(null, null);
}
}
}
```
上述示例中,首先定义了要编译的代码,然后使用 `CSharpCodeProvider` 类编译代码,并将编译后的程序集加载到内存中。最后,通过反射获取类型和方法,并执行该方法。
阅读全文
相关推荐















