zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    nginx原理及常用配置
    课程作业03-1
    Java动手动脑02
    Java课程作业02
    java课堂测试2
    Java验证码程序
    课程作业02-2
    课程作业02-1
    课程作业01
    《大道至简》第一章伪代码
  • 原文地址:https://www.cnblogs.com/wangbaohui/p/7122027.html
Copyright © 2011-2022 走看看