加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:03:05 所属栏目:百科 来源:网络整理
导读:本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 using System;using Microsoft.CSharp;using System.CodeDom.Compiler; class Program{ public static void Main() { // The C# code to execute string code = "using Syst

本文实例为大家分享了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();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读