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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

王宝会   2021-03-24 我要评论
想了解C#动态编译并执行字符串样例的相关内容吗,王宝会在本文为您仔细讲解C#动态编译并执行字符串的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,动态编译,字符串,下面大家一起来学习吧。

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();
 }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们