C#动态编译并执行字符串样例

作者:王宝会 时间:2022-02-10 22:26:53 

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下


using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
public static void Main()
{
 // The C# code to execute
 string code = "using System; " +
     "using System.IO; " +
     "public class MyClass{ " +
     " public static void PrintConsole(string message){ " +
     "  Console.WriteLine(message); " +
     " } " +
     "} ";

// Compiler and CompilerParameters
 CSharpCodeProvider codeProvider = new CSharpCodeProvider();
 CompilerParameters compParameters = new CompilerParameters();

// Compile the code
 CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code);

// Create a new instance of the class 'MyClass'// 有命名空间的,需要命名空间.类名
 object myClass = res.CompiledAssembly.CreateInstance("MyClass");

// Call the method 'PrintConsole' with the parameter 'Hello World'
 // "Hello World" will be written in console
 myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] {"Hello World" });

Console.Read();
}
}
标签:C#,动态编译,字符串
0
投稿

猜你喜欢

  • 使用C# 的webBrowser写模拟器时的javascript脚本调用问题

    2022-03-14 23:56:31
  • 使用Spring Data JDBC实现DDD聚合的示例代码

    2022-05-04 05:11:23
  • java图片缩放实现图片填充整个屏幕

    2021-06-09 18:30:07
  • Java八种基本变量作为类的成员变量的默认值操作

    2022-06-25 04:55:58
  • C#命令模式用法实例

    2021-10-21 12:46:02
  • IDEA 中使用 Hudi的示例代码

    2021-08-27 21:51:04
  • Java将Exception信息转为String字符串的方法

    2022-12-01 08:39:35
  • Mybatis代码生成器Mybatis Generator(MBG)实战详解

    2023-12-02 23:04:31
  • springMVC+ajax实现文件上传且带进度条实例

    2022-01-15 16:42:36
  • Fluent Mybatis零xml配置实现复杂嵌套查询

    2022-02-03 19:34:32
  • Java String源码分析并介绍Sting 为什么不可变

    2021-09-23 06:10:42
  • C# 通过反射获取类型的字段值及给字段赋值的操作

    2021-11-14 13:30:23
  • c#使用Dataset读取XML文件动态生成菜单的方法

    2022-07-14 22:52:20
  • 详解WPF中的APP生命周期以及全局异常捕获

    2022-12-10 11:54:27
  • java实现日期拆分的方法

    2023-06-19 00:28:59
  • Java类库BeanUtils组件使用方法及实例详解

    2022-09-28 00:37:49
  • Java中BorderLayout布局管理器的两种排列方式

    2022-03-14 08:04:35
  • MyBatis-Plus多表联查的实现方法(动态查询和静态查询)

    2023-11-23 22:26:45
  • 在IntelliJ IDEA中多线程并发代码的调试方法详解

    2022-01-09 03:05:45
  • spring boot集成smart-doc自动生成接口文档详解

    2023-11-28 23:08:02
  • asp之家 软件编程 m.aspxhome.com