c# 动态执行代码
时间: 2023-07-27 20:24:09 浏览: 221
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` 类编译代码,并将编译后的程序集加载到内存中。最后,通过反射获取类型和方法,并执行该方法。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-dosexec](https://img-home.csdnimg.cn/images/20210720083343.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)